I was reading the book of Ruby meta-programming. Three things that
author said about this concepts,which I didn't understand.
What private Really Means
Now that you know about self, you can cast a new light over
Ruby’s private keyword. Private methods are governed by a
single simple rule: you cannot call a private method with an
explicit receiver. In other words, every time you call a private
method, it must be on the implicit receiver—self. Let’s see a cor-
ner case:
class C
def public_method
self.private_method
end
private
def private_method; end
end
C.new.public_method
⇒
NoMethodError: private method ‘private_method' called [...]
You can make this code work by removing the self keyword.
This contrived example shows that private methods come from
two rules working together: first, you need an explicit receiver
to call a method on an object that is not **yourself**, and second,
private methods can be called only with an implicit receiver. Put
these two rules together, and you’ll see that you can only call
a private method on yourself. You can call this the “private rule.”
Q. What does author mean by **yourself** ?
Can object x call a private methodon object y if the two objects share
the same class? The answer is no, because no matter which class you
belong to, you still need an explicit receiver to call another object’s
method.
Q. Could anyone explain the above answer of the author? I didn't get his
point.
Can you call a private method that you inherited from a superclass?
The answer is yes, because you don’t need an explicit receiver
to call inherited methods on yourself.
Q.Could anyone explain the above answer of the author? I didn't get his
point.
···
--
Posted via http://www.ruby-forum.com/.