From: "Jesús Gabriel y Galán" Date: 2012-06-30T00:57:36+09:00 Subject: Re: Accessor Methods with a Twist On Fri, Jun 29, 2012 at 5:33 PM, Doug Jolley wrote: > I am surprised that the code shown below returns, 'Doug'.  I would > expect that it would return, 'Fred'.  Can someone please tell me why? > > @name = 'Doug' > > def name=(name) >  @name = name > end > def name() >  return @name > end > > name=('Fred') > puts(name()) name=('Fred') is interpreted as an assignment to a local variable called name, not the call to the method. When you have an "assignment-like" method (a method ending in the equals sign), you have to use self. to call it, otherwise Ruby will think you are assigning to a local variable: 1.9.2p290 :001 > def name=(name) 1.9.2p290 :002?> @name = name 1.9.2p290 :003?> end => nil 1.9.2p290 :004 > defined? name => nil 1.9.2p290 :005 > name=('fred') => "fred" 1.9.2p290 :006 > @name => nil 1.9.2p290 :007 > name => "fred" 1.9.2p290 :008 > self.name=('fred') => "fred" 1.9.2p290 :009 > @name => "fred" Jesus.