From: Kirk Haines Date: 2004-04-24T01:01:17+09:00 Subject: Re: attr_accessor vs. local variable On Sat, 24 Apr 2004, Its Me wrote: > Ruby not seem to predictably recognize attribute accessors (including > setters) as such unless preceded by "self.attr". But it recognizes other > self messages fine. I suspect this has something to do with its rule on what > is deemed a local variable. > > What rule / ambiguity causes this? > > class A > attr_accessor :x, :y > > def initialize > p x # local or @x? > x=5 # does not call self.x= > self.y=5 # sets @y > foo # calls self.foo > end > > def foo > p 'foo' > end > > end > > p A.new.x > p A.new.y This makes sense. When you 'p x', all ruby knows about at that point is the accessor method. So p x == p @x When you get to x=5, though, Ruby says, "Ah! A local variable" and assigns 5 to the local variable x. See below: enigodev src % irb irb(main):001:0> def x irb(main):002:1> 7 irb(main):003:1> end => nil irb(main):004:0> puts x 7 => nil irb(main):005:0> x = 4 => 4 irb(main):006:0> puts x 4 Kirk Haines