From: James Edward Gray II Date: 2005-07-03T00:40:05+09:00 Subject: Re: class variable leading a double life On Jul 2, 2005, at 9:55 AM, Amarison wrote: > Can someone please explain why the @var variable leads a double > life? One > for instances and one for the class itself? @var refers to an instance variable of the current "self" object. > class Test > def Test.inc > @var ||= 0 > @var += 1 > end Here self is Test. > def inc > @var ||= 0 > @var += 1 > end > end And here, self is an instance of Test. Two different objects, two different variables. > > puts Test.inc > > x = Test.new > puts x.inc > > y = Test.new > puts y.inc > > #------------- > > puts Test.inc > puts x.inc > puts y.inc If you want it to be the same variable in both places, you need a class variable: class Test @@var = 0 def Test.inc @@var += 1 end def inc @@var += 1 end end puts Test.inc x = Test.new puts x.inc y = Test.new puts y.inc #------------- puts Test.inc puts x.inc puts y.inc Hope that helps. James Edward Gray II