On 23.11.2011 17: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 #<A:0xb7756518>
>>      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
>
Thank you for your answer, saved me from future mistakes.