From: Peter Hickman Date: 2011-11-24T18:18:00+09:00 Subject: Re: private and protected I stand corrected. On 23 November 2011 14:12, Daniel Bye wrote: > On Wed, Nov 23, 2011 at 10:20:54PM +0900, Николай wrote: >> Could anybody explain me this, please? >> >> class First >>     def say >>         self.phrase >>     end >> >>     private >> >>     def phrase >>         'something' >>     end >> end >> >> a = First.new >> a.say >> # got >> NoMethodError: private method `b' called for # >>     from (irb):44:in `say' >>     from (irb):52 >>     from :0 >> >> If i write the same code with 'protected' instead of 'private' I got no >> error. >> If i write the same code with calling 'phrase' instead of 'self.phrase' >> in 'say' method I got no error again. > > A private method may only be called with an implicit receiver - in > self.phrase, self is explicit, which is why you get the exception. The > practical upshot of this is that private methods may only be called by the > current instance, because the implicit receiver is understood to be "self". > > Protected methods may be called by the current instance, instances of its > class or instances of it subclasses, and require an explicit receiver, > except when the receiver is the current instance. I would tend, even then, > to pass it explicitly to help make the code's intent clearer. > > This has been expressed much more elegantly in numerous places, so search > the web if I only served to confuse! > > Dan > > -- > Daniel Bye >                                                                     _ >                                              ASCII ribbon campaign ( ) >                                         - against HTML, vCards and  X >                                - proprietary attachments in e-mail / \ >