From: "David A. Black" Date: 2008-06-30T04:21:55+09:00 Subject: Re: implicit vs explicit self in private methods Hi -- On Mon, 30 Jun 2008, Stefano Crocco wrote: > On Sunday 29 June 2008, dusty wrote: >> I'm trying to understand the difference between implicitly and >> explicitly calling a private method and am hoping someone could shed >> some light on this for me. >> >> class Tester >> def public_hello_good >> say_hello >> end >> def public_hello_bad >> self.say_hello >> end >> private >> def say_hello >> "hello" >> end >> end >> >> irb(main):001:0> require 'tester' >> => true >> irb(main):002:0> a = Tester.new >> => # >> irb(main):003:0> a.public_hello_good >> => "hello" >> irb(main):004:0> a.public_hello_bad >> NoMethodError: private method `say_hello' called for # >> from ./tester.rb:6:in `public_hello_bad' >> from (irb):4 >> from :0 >> >> What I'm wondering is why does this not work when I call >> self.say_hello, but does work when I call say_hello? Since self is >> the receiver in both cases, it seems that they would both work. >> >> Anyone have any insight that they'd be willing to share on why it >> works like that? >> >> Thanks > > It's at the same time quite simple and quite confusing. It's simple because > the rule determining how a private method can be called is very short and > clear: you can only call a private method using the implicit receiver. It's > confusing because it seems natural to interpret the previous statement so that > it reads: you can only call a private method if the receiver is equal (in the > eql? sense) as the implicit receiver. However, this interpretation is wrong. > The words "only using the implicit receiver" should be taken literaly: if a > method is private, you can't call it using the dot notation > (receiver.method_name), even when the implicit and the explicit receiver are > the same thing. Unless it ends in = :-) David -- Rails training from David A. Black and Ruby Power and Light: ADVANCING WITH RAILS July 21-24 Edison, NJ See http://www.rubypal.com for details and updates!