[LRUG] Private methods

Kenneth Lee kenfodder at gmail.com
Mon Jan 26 15:00:51 PST 2009


Well I found the explanation, private methods can't be called with an
explicit receiver even if it is self:

http://weblog.jamisbuck.org/2007/2/23/method-visibility-in-ruby

I sometimes like to explicitly write self as it helps readability, but in
this case it breaks the sematics of the language.

2009/1/26 Kenneth Lee <kenfodder at gmail.com>

>  I've used Ruby for 3 years now and this just confused me suddenly about
> private methods:
>
> class Foo
>
>   def hello
>     self.p()
>   end
>
>   private
>
>     def p
>       puts 'world'
>     end
> end
>
> a = Foo.new
> a.hello
>
> This throws an exception which I'm not expecting!
> foo.rb:4:in `hello': private method `p' called for #<Foo:0x2911c>
> (NoMethodError)
>     from foo.rb:15
>
> However if I remove the "self." so the "self." is implied it works! I'm I
> going mad?
>
> class Foo
>
>   def hello
>     p()
>   end
>
>   private
>
>     def p
>       puts 'world'
>     end
> end
>
> a = Foo.new
> a.hello
>
> My version of ruby is: ruby 1.8.6 (2008-03-03 patchlevel 114)
> [universal-darwin9.0]
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lrug.org/pipermail/chat-lrug.org/attachments/20090126/04d9f2c5/attachment.html>


More information about the Chat mailing list