From: Robert Klemme Date: 2007-03-03T22:15:06+09:00 Subject: Re: Question about attr_accessor On 03.03.2007 13:55, 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? bar += 1 is translated to "bar = bar + 1". When Ruby sees "bar =" it takes bar to be a local variable. Hence you have to prefix with "self.". See: http://www.ruby-doc.org/docs/ProgrammingRuby/html/language.html#UO Kind regards robert