From: Daniel Bye Date: 2011-11-23T23:12:21+09:00 Subject: Re: private and protected --FFoLq8A0u+X9iRU8 Content-Type: text/plain; charset=utf-8 Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Wed, Nov 23, 2011 at 10:20:54PM +0900, =D0=9D=D0=B8=D0=BA=D0=BE=D0=BB=D0= =B0=D0=B9 wrote: > Could anybody explain me this, please? >=20 > class First > def say > self.phrase > end >=20 > private >=20 > def phrase > 'something' > end > end >=20 > a =3D First.new > a.say > # got > NoMethodError: private method `b' called for # > from (irb):44:in `say' > from (irb):52 > from :0 >=20 > If i write the same code with 'protected' instead of 'private' I got no= =20 > error. > If i write the same code with calling 'phrase' instead of 'self.phrase'= =20 > 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 --=20 Daniel Bye _ ASCII ribbon campaign ( ) - against HTML, vCards and X - proprietary attachments in e-mail / \ --FFoLq8A0u+X9iRU8 Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.11 (FreeBSD) iEYEARECAAYFAk7M/0EACgkQixf5fBYiFmpwKQCbB+Azkr7mT98HyB5Uc+Aqg6DL xIUAoLg/A7eRV6+QaJ3ipv+NK9bZhhxS =Y8Kj -----END PGP SIGNATURE----- --FFoLq8A0u+X9iRU8--