[LRUG] Private methods

Matt Wynne matt at mattwynne.net
Wed Jan 28 03:25:09 PST 2009


On 27 Jan 2009, at 09:35, Matthew Rudy Jacobs wrote:

> 2009/1/26 Kenneth Lee <kenfodder at gmail.com>:
>> 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.
>
>
> That's almost true,
> except private "=" methods work with a self.
>
> eg.
>
> def secret
>  @secret
> end
> private :secret
>
> def secret=(value)
>  @secret = value
> end
> private :secret=
>
>>> self.secret = 12
> => 12
>>> secret
> => 12
>
> else it is ambiguous whether you're calling a private writer method,
> or declaring a local variable
>
>>> secret = 24 # a local variable?
> => 24
>>> puts secret # if we just set a local variable, will this now print  
>>> the local variable, or the call to the private method?
>
> that's why I always seem to use "protected"
> as you say "self." is nice and unambiguous.
>
> Matthew Rudy

I always wondered what protected was for - that makes some sense.
http://blog.mattwynne.net/2008/07/24/c-ruby-culture-shock-1-private-methods-aint-so-private/

Matt Wynne
http://blog.mattwynne.net
http://www.songkick.com




More information about the Chat mailing list