James Edward Gray II wrote: > 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. > I thought that Test.inc was a class method that could be called without ever instantiating an object of class Test, and that therefore there would be no "self". Are you saying that Test is not just a class, but is also an instance of some other class? I don't understand, but then I'm just a newbie to Ruby. >> 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 > > >