Why is it that when you call a private method, you cannot use
Below is an example that works if you take out self before the method,
but fails with it in.
It is odd because using self should just a more explicit statement.
But either way the method is being sent to the same object.
Please let me know how you gurus wrap your heads around this
self.priv #why can’t you put the self in front of a private method?
@value = 100
i = TestPrivate.new
callPriv': private methodpriv’ called for #<TestPrivate:
~> from -:18
In Ruby, private means that the method cannot be called with an
explicit receiver (that includes “self”). This is a bit different
then languages like C++ and Java which use private/protected to
control calling in inheritance chains. Remember, Ruby is all about the
callers and receivers. If you leave off the “self.” at the front, then
self is implicit (which is allowed for private methods. Try this:
puts “Explicit callers are ok”
puts “Implicit callers only!”
my_obj = MyClass.new
my_other_obj = MyClass.new
Josh, thanks for the clarification. I guess I just have to accept the
syntax for the private method calls. But it is hard for me to
understand why calling a private method on its own–which has to look
up self to use as a receiver, is any different than me just giving it
the receiver of self. Either way the same object is being used as the
receiver. So there must be something strange about the way private is
implemented that makes it not ever take receivers, even if you give it
the receiver that it is going to lookup and use. Okay, I can tell I am
just grumbling about something that I should just accept. Sorry.