class Example private def example_test puts 'Hello' end end e = Example.new e.example_test
This, of course, will not work, because we specified the explicit recipient - an instance of Example ( e ), and this contradicts the "private rule".
But I cannot understand why in Ruby you cannot do this:
class Foo def public_m self.private_m # <= end private def private_m puts 'Hello' end end Foo.new.public_m
The current object inside the public_m method public_m (i.e. self ) is an instance of Foo. So why is it forbidden? To fix this, I need to change self.private_m to private_m . But why is this different and not a self instance of Foo inside public_m ? And who is the private_m voice recipient? Is it not self - in fact, you omit it because Ruby will do it for you (it will call private_m on itself)?
I hope I didnβt embarrass him too much, I still got to Ruby.
EDIT: Thanks for all the answers. By combining them all together, I was able (eventually) to reveal the obvious (and not so obvious for someone who had never seen things like Ruby): self itself can be an explicit and implicit receiver, and that makes a difference. Thus, there are two rules if you want to call a private method: self must be an implicit receiver, and that it must itself be an instance of the current class ( Example in this case), and this only happens when self if inside the definition of the instance method during execution of this method). Please correct me if I am wrong.
class Example
A message to anyone who can find this question during google runs: it can be useful - http://weblog.jamisbuck.org/2007/2/23/method-visibility-in-ruby
ruby access-specifier
Ernest Nov 27 '10 at 18:34 2010-11-27 18:34
source share