Top-level method can be accessed from another class in Ruby? - ruby

How is it possible that if I define a method in the Object class (which is defined as private), I am able to call it from inside another class? I mean, when I call say_hello from inside the class Dog, how is it resolved if say_hello is a top-level defined method and therefore is private to the Object class? I know the Object class is in the method lookup of all the classes, but if the method is private it should not be accessible right?
def say_hello
p "Hello"
end
class Dog
def test_hello
say_hello
end
end
prova = Dog.new
prova.test_hello
I guess an easier explanation of my doubt would be: Why can I call a private method of a parent from a child?
class Animal
private
def prova
p "hello"
end
end
class Dog < Animal
def test_hello
prova
end
end
prova = Dog.new
prova.test_hello

Remember Dog inherits from Object, giving it access to Objects methods. You can extend the Object class all you want.
See answer to: How to extend class Object in Rails?

but if the method is private it should not be accessible right?
What makes you think that?
Private methods can only be called with an implicit receiver. You are calling it with an implicit receiver. Ergo, it should work … and it does.

Related

Ruby: when do we need protected methods? [duplicate]

Before I read this article, I thought access control in Ruby worked like this:
public - can be accessed by any object (e.g. Obj.new.public_method)
protected - can only be accessed from within the object itself, as well as any subclasses
private - same as protected, but the method doesn't exist in subclasses
However, it appears that protected and private act the same, except for the fact that you can't call private methods with an explicit receiver (i.e. self.protected_method works, but self.private_method doesn't).
What's the point of this? When is there a scenario when you wouldn't want your method called with an explicit receiver?
protected methods can be called by any instance of the defining class or its subclasses.
private methods can be called only from within the calling object. You cannot access another instance's private methods directly.
Here is a quick practical example:
def compare_to(x)
self.some_method <=> x.some_method
end
some_method cannot be private here. It must be protected because you need it to support explicit receivers. Your typical internal helper methods can usually be private since they never need to be called like this.
It is important to note that this is different from the way Java or C++ works. private in Ruby is similar to protected in Java/C++ in that subclasses have access to the method. In Ruby, there is no way to restrict access to a method from its subclasses like you can with private in Java.
Visibility in Ruby is largely a "recommendation" anyways since you can always gain access to a method using send:
irb(main):001:0> class A
irb(main):002:1> private
irb(main):003:1> def not_so_private_method
irb(main):004:2> puts "Hello World"
irb(main):005:2> end
irb(main):006:1> end
=> nil
irb(main):007:0> foo = A.new
=> #<A:0x31688f>
irb(main):009:0> foo.send :not_so_private_method
Hello World
=> nil
The difference
Anyone can call your public methods.
You can call your protected methods, or another member of your class (or a descendant class) can call your protected methods from the outside. Nobody else can.
Only you can call your private methods, because they can only be called with an implicit receiver of self. Even you cannot call self.some_private_method; you must call private_method with self implied.
iGEL points out: "There is one exception, however. If you have a private method age=, you can (and have to) call it with self to separate it from local variables."
Since Ruby 2.7 the self receiver can be explicit, self.some_private_method is allowed. (Any other explicit receiver is still disallowed, even if the runtime value is the same as self.)
In Ruby, these distinctions are just advice from one programmer to another. Non-public methods are a way of saying "I reserve the right to change this; don't depend on it." But you still get the sharp scissors of send and can call any method you like.
A brief tutorial
# dwarf.rb
class Dwarf
include Comparable
def initialize(name, age, beard_strength)
#name = name
#age = age
#beard_strength = beard_strength
end
attr_reader :name, :age, :beard_strength
public :name
private :age
protected :beard_strength
# Comparable module will use this comparison method for >, <, ==, etc.
def <=>(other_dwarf)
# One dwarf is allowed to call this method on another
beard_strength <=> other_dwarf.beard_strength
end
def greet
"Lo, I am #{name}, and have mined these #{age} years.\
My beard is #{beard_strength} strong!"
end
def blurt
# Not allowed to do this: private methods can't have an explicit receiver
"My age is #{self.age}!"
end
end
require 'irb'; IRB.start
Then you can run ruby dwarf.rb and do this:
gloin = Dwarf.new('Gloin', 253, 7)
gimli = Dwarf.new('Gimli', 62, 9)
gloin > gimli # false
gimli > gloin # true
gimli.name # 'Gimli'
gimli.age # NoMethodError: private method `age'
called for #<Dwarf:0x007ff552140128>
gimli.beard_strength # NoMethodError: protected method `beard_strength'
called for #<Dwarf:0x007ff552140128>
gimli.greet # "Lo, I am Gimli, and have mined these 62 years.\
My beard is 9 strong!"
gimli.blurt # private method `age' called for #<Dwarf:0x007ff552140128>
Private methods in Ruby:
If a method is private in Ruby, then it cannot be called by an explicit receiver (object). It can only be call implicitly. It can be called implicitly by the class in which it has been described in as well as by the subclasses of this class.
The following examples will illustrate it better:
1) A Animal class with private method class_name
class Animal
def intro_animal
class_name
end
private
def class_name
"I am a #{self.class}"
end
end
In this case:
n = Animal.new
n.intro_animal #=>I am a Animal
n.class_name #=>error: private method `class_name' called
2) A subclass of Animal called Amphibian:
class Amphibian < Animal
def intro_amphibian
class_name
end
end
In this case:
n= Amphibian.new
n.intro_amphibian #=>I am a Amphibian
n.class_name #=>error: private method `class_name' called
As you can see, private methods can be called only implicitly. They cannot be called by explicit receivers. For the same reason, private methods cannot be called outside the hierarchy of the defining class.
Protected Methods in Ruby:
If a method is protected in Ruby, then it can be called implicitly by both the defining class and its subclasses. Additionally they can also be called by an explicit receiver as long as the receiver is self or of same class as that of self:
1) A Animal class with protected method protect_me
class Animal
def animal_call
protect_me
end
protected
def protect_me
p "protect_me called from #{self.class}"
end
end
In this case:
n= Animal.new
n.animal_call #=> protect_me called from Animal
n.protect_me #=>error: protected method `protect_me' called
2) A mammal class which is inherited from animal class
class Mammal < Animal
def mammal_call
protect_me
end
end
In this case
n= Mammal.new
n.mammal_call #=> protect_me called from Mammal
3) A amphibian class inherited from Animal class (same as mammal class)
class Amphibian < Animal
def amphi_call
Mammal.new.protect_me #Receiver same as self
self.protect_me #Receiver is self
end
end
In this case
n= Amphibian.new
n.amphi_call #=> protect_me called from Mammal
#=> protect_me called from Amphibian
4) A class called Tree
class Tree
def tree_call
Mammal.new.protect_me #Receiver is not same as self
end
end
In this case:
n= Tree.new
n.tree_call #=>error: protected method `protect_me' called for #<Mammal:0x13410c0>
Consider a private method in Java. It can be called from within the same class, of course, but it can also be called by another instance of that same class:
public class Foo {
private void myPrivateMethod() {
//stuff
}
private void anotherMethod() {
myPrivateMethod(); //calls on self, no explicit receiver
Foo foo = new Foo();
foo.myPrivateMethod(); //this works
}
}
So -- if the caller is a different instance of my same class -- my private method is actually accessible from the "outside", so to speak. This actually makes it seem not all that private.
In Ruby, on the other hand, a private method really is meant to be private only to the current instance. This is what removing the option of an explicit receiver provides.
On the other hand, I should certainly point out that it's pretty common in the Ruby community to not use these visibility controls at all, given that Ruby gives you ways to get around them anyway. Unlike in the Java world, the tendency is to make everything accessible and trust other developers not to screw things up.
What's the difference?
Private Methods Explained
#freddie = Person.new
#freddie.hows_it_going?
# => "oh dear, i'm in great pain!"
class Person
# public method
def hows_it_going?
how_are_your_underpants_feeling?
end
private
def how_are_your_underpants_feeling? # private method
puts "oh dear, i'm in great pain!"
end
end
We can ask Freddie how things are going given it's a public method. That's perfectly valid. And it's normal and accepted.
But...the only person who can know how Freddie's underpants situation is, is Freddie himself. It would not do for random strangers to reach into Freddy's underpants - no, no -- it's very, very private, and we don't want to expose what's private to the outside world. In other words, we may not want to expose mutable data, to any caller in the world. Someone could mutate a value, and we'd be in a world of pain trying to discover where the bug came from.
#freddie.how_are_your_underpants_feeling?
# => # NoMethodError: private method `how_are_your_underpants_feeling?' called
Protected Methods Explained
Consider this:
class Person
protected
def hand_over_the_credit_card! # protected method
puts "Lawd have mercy. Whatever. Here it is: 1234-4567-8910"
end
end
class Rib < Person
end
class Wife < Rib # wife inherits from Rib
def i_am_buying_another_handbag_with_your_card(husband)
husband.hand_over_the_credit_card! # equalityInAction
end
end
#husband = Person.new
#mrs = Wife.new
#mrs.i_am_buying_another_handbag_with_your_card(#husband)
# => puts "Lawd have mercy. Whatever. Here it is: 1234-4567-8910"
We're somewhat ok with mrs getting our credit card details, given mrs is flesh of our flesh, inherited from Person, so she can blow it on some shoes etc., but we don't want random individuals getting access to our credit card details.
If we tried to do that outside the subclass, it would fail:
#mrs = Wife.new
#mrs.gimme_your_credit_card!
# => protected method hand_over_the_credit_card! called for #<Wife:0x00005567b5865818> (NoMethodError)
Summary
private methods can only be called from within, and without "an explicit receiver". (Strictly speaking, you can access a private method using a little bit of ruby magic, but I'm going to ignore that for the moment).
protected methods can be called within sub-classes.
I used the examples/analogies to help you vividly remember.
Part of the reason why private methods can be accessed by subclasses in Ruby is that Ruby inheritance with classes is thin sugarcoating over Module includes - in Ruby, a class, in fact, is a kind of module that provides inheritance, etc.
http://ruby-doc.org/core-2.0.0/Class.html
What this means is that basically a subclass "includes" the parent class so that effectively the parent class's functions, including private functions, are defined in the subclass as well.
In other programming languages, calling a method involves bubbling the method name up a parent class hierarchy and finding the first parent class that responds to the method. By contrast, in Ruby, while the parent class hierarchy is still there, the parent class's methods are directly included into the list of methods of the subclass has defined.
Comparison of access controls of Java against Ruby: If method is declared private in Java, it can only be accessed by other methods within the same class. If a method is declared protected it can be accessed by other classes which exist within the same package as well as by subclasses of the class in a different package. When a method is public it is visible to everyone. In Java, access control visibility concept depends on where these classes lie's in the inheritance/package hierarchy.
Whereas in Ruby, the inheritance hierarchy or the package/module don't fit. It's all about which object is the receiver of a method.
For a private method in Ruby, it can never be called with an explicit receiver. We can (only) call the private method with an implicit receiver.
This also means we can call a private method from within a class it is declared in as well as all subclasses of this class.
class Test1
def main_method
method_private
end
private
def method_private
puts "Inside methodPrivate for #{self.class}"
end
end
class Test2 < Test1
def main_method
method_private
end
end
Test1.new.main_method
Test2.new.main_method
Inside methodPrivate for Test1
Inside methodPrivate for Test2
class Test3 < Test1
def main_method
self.method_private #We were trying to call a private method with an explicit receiver and if called in the same class with self would fail.
end
end
Test1.new.main_method
This will throw NoMethodError
You can never call the private method from outside the class hierarchy where it was defined.
Protected method can be called with an implicit receiver, as like private. In addition protected method can also be called by an explicit receiver (only) if the receiver is "self" or "an object of the same class".
class Test1
def main_method
method_protected
end
protected
def method_protected
puts "InSide method_protected for #{self.class}"
end
end
class Test2 < Test1
def main_method
method_protected # called by implicit receiver
end
end
class Test3 < Test1
def main_method
self.method_protected # called by explicit receiver "an object of the same class"
end
end
InSide method_protected for Test1
InSide method_protected for Test2
InSide method_protected for Test3
class Test4 < Test1
def main_method
Test2.new.method_protected # "Test2.new is the same type of object as self"
end
end
Test4.new.main_method
class Test5
def main_method
Test2.new.method_protected
end
end
Test5.new.main_method
This would fail as object Test5 is not subclass of Test1
Consider Public methods with maximum visibility
Summary
Public: Public methods have maximum visibility
Protected: Protected method can be called with an implicit receiver, as like private. In addition protected method can also be called by an explicit receiver (only) if the receiver is "self" or "an object of the same class".
Private: For a private method in Ruby, it can never be called with an explicit receiver. We can (only) call the private method with an implicit receiver. This also means we can call a private method from within a class it is declared in as well as all subclasses of this class.
First Three types of access specifiers and those define thier scope.
Public -> Access anywhere out side the class.
Private -> Can not access outside the class.
Protected -> This Method not access anywhere this method define
scope.
But I have a solution for this problem for all method how to access explain in depth.
class Test
attr_reader :name
def initialize(name)
#name = name
end
def add_two(number)
#number = number
end
def view_address
address("Anyaddress")
end
private
def address(add)
#add = add
end
protected
def user_name(name)
# p 'call method'
#name = name
end
end
class Result < Test
def new_user
user_name("test355")
end
end
Object List
p test = Test.new("test")
p test.name
p test.add_two(3)
List item
p test.view_address
p r = Result.new("")
p r.new_user

self vs class name for class methods in inheritance

In this code:
class Dog
def self.bark
print "woof"
end
end
class Little_dog < Dog
end
Little_dog.bark
the method is inherited from a generalised class that references self. But the next patch of code:
class Dog
def Dog.bark
print "woof"
end
end
class Little_dog < Dog
end
Little_dog.bark
also works. I was expecting it to give me an error, but it didn't.
How does self refer to the class method under class inheritance? Why does the little_dog class have a class method bark in the second example when I only defined it as a class method of Dog?
self is widely used in Ruby Metaprogramming.
From Metaprogramming Ruby book:
Every line of Ruby code is executed inside an object—the so–called
current object. The current object is also known as self, because
you can access it with the self keyword.
Only one object can take the role of self at a given time, but no
object holds that role for a long time. In particular, when you call a
method, the receiver becomes self. From that moment on, all instance
variables are instance variables of self, and all methods called
without an explicit receiver are called on self. As soon as your code
explicitly calls a method on some other object, that other object
becomes self.
So, in code:
class Dog
# self represents the class object i.e: Dog. Which is an instance of Class.
# `bark` will be treated as class method
def self.bark
print "woof"
end
end
can also be written as:
class Dog
# Dog is an instance of Class.
# `bark` will be treated as class method
def Dog.bark
print "woof"
end
end
Inheritance allows a subclass to use features of its parent class. That's why you can access bark method in Little_dog class since it is inherited Dog class:
class Little_dog < Dog
# has `bark` as a class method because of Dog
end
Ruby style guide tip: In Ruby it's considered as a best practice to use CamelCase convention for naming classes and modules.
When you're defining class method it actually doesn't matter if you use
Dog.bark
or
self.bark
Both method defines class method which will be inherited by subclasses.
Only difference is when you will be changing name of class Dog to something else, like BigDog - when you use Dog.bark it obviously needs to be changed to BigDog.bark.
When using self method definition, self.bark will still work.

Ruby dynamically instantiate class

How to reference to a class within a static method?
class Car
def self.new_from_xml(xml)
instance = self.class.new
#do some stuff with xml
instance
end
end
class Mercedes < Car
end
class Porsche < Car
end
IRB:
Mercedes.new_from_xml(somedata) # Output is #<Class:...>, should be #<Mercedes:...>
Porsche.new_from_xml(somedata) # Output is #<Class:...>, should be #<Porsche:...>
Instead of
instance=self.class.new
just write
instance = new
Why is this?
Well, in first place, you have to understand that you are calling a class method, thus you are at a class level already. The .new method is a class method, so you can call it directly without calling self.class.new.
Why does self.class.new return Class?
Because the class of the class Car is Class (I know, sounds weird ;), because classes in Ruby are instances of Class.
This is actually a pretty deep concept, I recommend you read more about it. One nice reference I have read is the book Metaprogramming Ruby by Paolo Perrotta (ISBN-10: 1934356476) [1].
http://www.amazon.com/Metaprogramming-Ruby-Program-Like-Pros/dp/1934356476
Since you are already in a class method, you should use self.new (or simply new, as #tokland wrote) instead of self.class.new:
class Car
def self.new_from_xml(xml)
instance = new
#do some stuff with xml
end
end
class Mercedes < Car
end
class Porsche < Car
end
p Mercedes.new_from_xml(nil) #=> #<Mercedes:0x007f042d0db208>
p Porsche.new_from_xml(nil) #=> #<Porsche:0x007f042d0db118>
From a comment to this answer: Why does self.class reference to class? What's the logic here?
Inside a class block self references the class you are editing:
class Car
puts self #=> writes Car
end
Using def self.new_from_xml it is like if you are declaring def Car.new_from_xml, that is a method of the Car object (which is an instance of Class); so inside new_from_xml self coincides with Car.

class methods syntax in ruby

the ruby book I'm reading has confused me a bit. If I do the following, I understand completely why the code throws an error;
class Person
def show_name
puts #name
end
end
person = Person.new
person.show_name
Person.show_name #(note the capital P) this line falls over
It throws an error stating that the Person class does not have a method called show_name, because it is an instance method. I understand this completely. The book then throws in this example;
class Class
def add_accessor(accessor_name)
self.class_eval %Q{attr_accessor :#{accessor_name}}
end
end
class Person
end
person = Person.new
Person.add_accessor :name #note the capital P
Person.add_accessor :age #capital P here too
person.name = "Mikey"
person.age = 30
puts person.name
and goes on to state how cool it is that you can add methods to classes dynamically. What I don't understand is why I am suddenly allowed to call the "add_accessor" method as a class method (with a capital P) when the method itself isn't defined as such? I thought all class methods had to be declared like this?
class Math
def self.PI
3.141
end
end
puts Math.PI
Is anyone able to enlighten me?
Ruby classes are objects like everything else to. Your Person class is really an object of class Class, which in turn inherits from class Module. When you add a method to class Class as an instance method, you are providing a new method for all classes.
If you had declared it with a def in Person, it would not be callable without an object. To add class methods for one class, but not all, you must prepend the method name with self or the name of the class:
class Person
def instance_method
end
def self.class_method
end
def Person.other_class_method
end
end
When you declare the method as self.class_method you are declaring your method to be a singleton method on the class object. self in a class or module declaration refers to the class object, which is why self. and Person. are the same.
When dealing with Ruby, just remember everything is an object, everything has methods. There are no functions in Ruby either, despite appearances to the contrary. Methods and objects, always.
Look at this:
person.instance_of?(Person) #=> true
Person.instance_of?(Class) #=> true
You have defined an instance method add_accessor for all the instances of the class Class, so Person class can use that method because it is an instance of Class.
I recommend yout to take a look at metaprogramming and Ruby Object Model.
Hoep this helps
You're extending the Class class, and all of your classes, like Person, are instances of Class (Yes, classes are instances of the Class class. They're ordinary objects).
So when you call Person.add_accessor, you're calling the instance method Class#add_accessor.
because Person (with capital P ) is an instance of the class Class.

Why does Ruby have both private and protected methods?

Before I read this article, I thought access control in Ruby worked like this:
public - can be accessed by any object (e.g. Obj.new.public_method)
protected - can only be accessed from within the object itself, as well as any subclasses
private - same as protected, but the method doesn't exist in subclasses
However, it appears that protected and private act the same, except for the fact that you can't call private methods with an explicit receiver (i.e. self.protected_method works, but self.private_method doesn't).
What's the point of this? When is there a scenario when you wouldn't want your method called with an explicit receiver?
protected methods can be called by any instance of the defining class or its subclasses.
private methods can be called only from within the calling object. You cannot access another instance's private methods directly.
Here is a quick practical example:
def compare_to(x)
self.some_method <=> x.some_method
end
some_method cannot be private here. It must be protected because you need it to support explicit receivers. Your typical internal helper methods can usually be private since they never need to be called like this.
It is important to note that this is different from the way Java or C++ works. private in Ruby is similar to protected in Java/C++ in that subclasses have access to the method. In Ruby, there is no way to restrict access to a method from its subclasses like you can with private in Java.
Visibility in Ruby is largely a "recommendation" anyways since you can always gain access to a method using send:
irb(main):001:0> class A
irb(main):002:1> private
irb(main):003:1> def not_so_private_method
irb(main):004:2> puts "Hello World"
irb(main):005:2> end
irb(main):006:1> end
=> nil
irb(main):007:0> foo = A.new
=> #<A:0x31688f>
irb(main):009:0> foo.send :not_so_private_method
Hello World
=> nil
The difference
Anyone can call your public methods.
You can call your protected methods, or another member of your class (or a descendant class) can call your protected methods from the outside. Nobody else can.
Only you can call your private methods, because they can only be called with an implicit receiver of self. Even you cannot call self.some_private_method; you must call private_method with self implied.
iGEL points out: "There is one exception, however. If you have a private method age=, you can (and have to) call it with self to separate it from local variables."
Since Ruby 2.7 the self receiver can be explicit, self.some_private_method is allowed. (Any other explicit receiver is still disallowed, even if the runtime value is the same as self.)
In Ruby, these distinctions are just advice from one programmer to another. Non-public methods are a way of saying "I reserve the right to change this; don't depend on it." But you still get the sharp scissors of send and can call any method you like.
A brief tutorial
# dwarf.rb
class Dwarf
include Comparable
def initialize(name, age, beard_strength)
#name = name
#age = age
#beard_strength = beard_strength
end
attr_reader :name, :age, :beard_strength
public :name
private :age
protected :beard_strength
# Comparable module will use this comparison method for >, <, ==, etc.
def <=>(other_dwarf)
# One dwarf is allowed to call this method on another
beard_strength <=> other_dwarf.beard_strength
end
def greet
"Lo, I am #{name}, and have mined these #{age} years.\
My beard is #{beard_strength} strong!"
end
def blurt
# Not allowed to do this: private methods can't have an explicit receiver
"My age is #{self.age}!"
end
end
require 'irb'; IRB.start
Then you can run ruby dwarf.rb and do this:
gloin = Dwarf.new('Gloin', 253, 7)
gimli = Dwarf.new('Gimli', 62, 9)
gloin > gimli # false
gimli > gloin # true
gimli.name # 'Gimli'
gimli.age # NoMethodError: private method `age'
called for #<Dwarf:0x007ff552140128>
gimli.beard_strength # NoMethodError: protected method `beard_strength'
called for #<Dwarf:0x007ff552140128>
gimli.greet # "Lo, I am Gimli, and have mined these 62 years.\
My beard is 9 strong!"
gimli.blurt # private method `age' called for #<Dwarf:0x007ff552140128>
Private methods in Ruby:
If a method is private in Ruby, then it cannot be called by an explicit receiver (object). It can only be call implicitly. It can be called implicitly by the class in which it has been described in as well as by the subclasses of this class.
The following examples will illustrate it better:
1) A Animal class with private method class_name
class Animal
def intro_animal
class_name
end
private
def class_name
"I am a #{self.class}"
end
end
In this case:
n = Animal.new
n.intro_animal #=>I am a Animal
n.class_name #=>error: private method `class_name' called
2) A subclass of Animal called Amphibian:
class Amphibian < Animal
def intro_amphibian
class_name
end
end
In this case:
n= Amphibian.new
n.intro_amphibian #=>I am a Amphibian
n.class_name #=>error: private method `class_name' called
As you can see, private methods can be called only implicitly. They cannot be called by explicit receivers. For the same reason, private methods cannot be called outside the hierarchy of the defining class.
Protected Methods in Ruby:
If a method is protected in Ruby, then it can be called implicitly by both the defining class and its subclasses. Additionally they can also be called by an explicit receiver as long as the receiver is self or of same class as that of self:
1) A Animal class with protected method protect_me
class Animal
def animal_call
protect_me
end
protected
def protect_me
p "protect_me called from #{self.class}"
end
end
In this case:
n= Animal.new
n.animal_call #=> protect_me called from Animal
n.protect_me #=>error: protected method `protect_me' called
2) A mammal class which is inherited from animal class
class Mammal < Animal
def mammal_call
protect_me
end
end
In this case
n= Mammal.new
n.mammal_call #=> protect_me called from Mammal
3) A amphibian class inherited from Animal class (same as mammal class)
class Amphibian < Animal
def amphi_call
Mammal.new.protect_me #Receiver same as self
self.protect_me #Receiver is self
end
end
In this case
n= Amphibian.new
n.amphi_call #=> protect_me called from Mammal
#=> protect_me called from Amphibian
4) A class called Tree
class Tree
def tree_call
Mammal.new.protect_me #Receiver is not same as self
end
end
In this case:
n= Tree.new
n.tree_call #=>error: protected method `protect_me' called for #<Mammal:0x13410c0>
Consider a private method in Java. It can be called from within the same class, of course, but it can also be called by another instance of that same class:
public class Foo {
private void myPrivateMethod() {
//stuff
}
private void anotherMethod() {
myPrivateMethod(); //calls on self, no explicit receiver
Foo foo = new Foo();
foo.myPrivateMethod(); //this works
}
}
So -- if the caller is a different instance of my same class -- my private method is actually accessible from the "outside", so to speak. This actually makes it seem not all that private.
In Ruby, on the other hand, a private method really is meant to be private only to the current instance. This is what removing the option of an explicit receiver provides.
On the other hand, I should certainly point out that it's pretty common in the Ruby community to not use these visibility controls at all, given that Ruby gives you ways to get around them anyway. Unlike in the Java world, the tendency is to make everything accessible and trust other developers not to screw things up.
What's the difference?
Private Methods Explained
#freddie = Person.new
#freddie.hows_it_going?
# => "oh dear, i'm in great pain!"
class Person
# public method
def hows_it_going?
how_are_your_underpants_feeling?
end
private
def how_are_your_underpants_feeling? # private method
puts "oh dear, i'm in great pain!"
end
end
We can ask Freddie how things are going given it's a public method. That's perfectly valid. And it's normal and accepted.
But...the only person who can know how Freddie's underpants situation is, is Freddie himself. It would not do for random strangers to reach into Freddy's underpants - no, no -- it's very, very private, and we don't want to expose what's private to the outside world. In other words, we may not want to expose mutable data, to any caller in the world. Someone could mutate a value, and we'd be in a world of pain trying to discover where the bug came from.
#freddie.how_are_your_underpants_feeling?
# => # NoMethodError: private method `how_are_your_underpants_feeling?' called
Protected Methods Explained
Consider this:
class Person
protected
def hand_over_the_credit_card! # protected method
puts "Lawd have mercy. Whatever. Here it is: 1234-4567-8910"
end
end
class Rib < Person
end
class Wife < Rib # wife inherits from Rib
def i_am_buying_another_handbag_with_your_card(husband)
husband.hand_over_the_credit_card! # equalityInAction
end
end
#husband = Person.new
#mrs = Wife.new
#mrs.i_am_buying_another_handbag_with_your_card(#husband)
# => puts "Lawd have mercy. Whatever. Here it is: 1234-4567-8910"
We're somewhat ok with mrs getting our credit card details, given mrs is flesh of our flesh, inherited from Person, so she can blow it on some shoes etc., but we don't want random individuals getting access to our credit card details.
If we tried to do that outside the subclass, it would fail:
#mrs = Wife.new
#mrs.gimme_your_credit_card!
# => protected method hand_over_the_credit_card! called for #<Wife:0x00005567b5865818> (NoMethodError)
Summary
private methods can only be called from within, and without "an explicit receiver". (Strictly speaking, you can access a private method using a little bit of ruby magic, but I'm going to ignore that for the moment).
protected methods can be called within sub-classes.
I used the examples/analogies to help you vividly remember.
Part of the reason why private methods can be accessed by subclasses in Ruby is that Ruby inheritance with classes is thin sugarcoating over Module includes - in Ruby, a class, in fact, is a kind of module that provides inheritance, etc.
http://ruby-doc.org/core-2.0.0/Class.html
What this means is that basically a subclass "includes" the parent class so that effectively the parent class's functions, including private functions, are defined in the subclass as well.
In other programming languages, calling a method involves bubbling the method name up a parent class hierarchy and finding the first parent class that responds to the method. By contrast, in Ruby, while the parent class hierarchy is still there, the parent class's methods are directly included into the list of methods of the subclass has defined.
Comparison of access controls of Java against Ruby: If method is declared private in Java, it can only be accessed by other methods within the same class. If a method is declared protected it can be accessed by other classes which exist within the same package as well as by subclasses of the class in a different package. When a method is public it is visible to everyone. In Java, access control visibility concept depends on where these classes lie's in the inheritance/package hierarchy.
Whereas in Ruby, the inheritance hierarchy or the package/module don't fit. It's all about which object is the receiver of a method.
For a private method in Ruby, it can never be called with an explicit receiver. We can (only) call the private method with an implicit receiver.
This also means we can call a private method from within a class it is declared in as well as all subclasses of this class.
class Test1
def main_method
method_private
end
private
def method_private
puts "Inside methodPrivate for #{self.class}"
end
end
class Test2 < Test1
def main_method
method_private
end
end
Test1.new.main_method
Test2.new.main_method
Inside methodPrivate for Test1
Inside methodPrivate for Test2
class Test3 < Test1
def main_method
self.method_private #We were trying to call a private method with an explicit receiver and if called in the same class with self would fail.
end
end
Test1.new.main_method
This will throw NoMethodError
You can never call the private method from outside the class hierarchy where it was defined.
Protected method can be called with an implicit receiver, as like private. In addition protected method can also be called by an explicit receiver (only) if the receiver is "self" or "an object of the same class".
class Test1
def main_method
method_protected
end
protected
def method_protected
puts "InSide method_protected for #{self.class}"
end
end
class Test2 < Test1
def main_method
method_protected # called by implicit receiver
end
end
class Test3 < Test1
def main_method
self.method_protected # called by explicit receiver "an object of the same class"
end
end
InSide method_protected for Test1
InSide method_protected for Test2
InSide method_protected for Test3
class Test4 < Test1
def main_method
Test2.new.method_protected # "Test2.new is the same type of object as self"
end
end
Test4.new.main_method
class Test5
def main_method
Test2.new.method_protected
end
end
Test5.new.main_method
This would fail as object Test5 is not subclass of Test1
Consider Public methods with maximum visibility
Summary
Public: Public methods have maximum visibility
Protected: Protected method can be called with an implicit receiver, as like private. In addition protected method can also be called by an explicit receiver (only) if the receiver is "self" or "an object of the same class".
Private: For a private method in Ruby, it can never be called with an explicit receiver. We can (only) call the private method with an implicit receiver. This also means we can call a private method from within a class it is declared in as well as all subclasses of this class.
First Three types of access specifiers and those define thier scope.
Public -> Access anywhere out side the class.
Private -> Can not access outside the class.
Protected -> This Method not access anywhere this method define
scope.
But I have a solution for this problem for all method how to access explain in depth.
class Test
attr_reader :name
def initialize(name)
#name = name
end
def add_two(number)
#number = number
end
def view_address
address("Anyaddress")
end
private
def address(add)
#add = add
end
protected
def user_name(name)
# p 'call method'
#name = name
end
end
class Result < Test
def new_user
user_name("test355")
end
end
Object List
p test = Test.new("test")
p test.name
p test.add_two(3)
List item
p test.view_address
p r = Result.new("")
p r.new_user

Resources