From: Harry Date: 2007-03-03T22:11:58+09:00 Subject: Re: Question about attr_accessor On 3/3/07, Roland Swingler wrote: > Hi, > > I came across something unexpected today, and wondered if anyone could > explain it to me. If I have this class: > > class Foo > def initialize > @bar = 0 > end > > attr_accessor :bar > > def add > bar += 1 > end > end > > then the "add" function doesn't work - it complains about a nil > object. You have to specifically put "self.bar += 1". Why is that - I > thought that the "self" was implicitly there? > > Doing: > > f = Foo.new > f.add > > works as the class stands, so you only seem to need the self if you > are calling the accessor from within your class. > > Confused... > > TIA > Roland > > > attr_accessor :bar refers to the instance variable @bar. bar and @bar are not the same. Harry -- http://www.kakueki.com/ruby/list.html Japanese Ruby List Subjects in English