From: Garance A Drosihn Date: 2003-08-21T21:19:09+09:00 Subject: Re: Class variables - a surprising result At 6:33 PM +0900 8/21/03, Jason Williams wrote: > class Sup > @@x = "A" > def test > print @@x > end > end > > class Sub1 < Sup > @@x = "B" > end > > class Sub2 < Sup > @@x = "C" > end > > Sup.new.test > Sub1.new.test > Sub2.new.test > >I expect this to print "ABC", and yet it prints "CCC". >Why is this? That's what I would expect to happen, although I am not sure I could give a good explanation as to why it is "obvious" that it should work that way. As to what exactly is happening, the assignments to @@x are not inside any method. The assignments are processed as they are read in, not in the order that '.new' (or any other method) is called on any of the classes. Perhaps the following will give you a better idea of why you ended up with 'CCC': # - - - - start class Sup @@x = "A" @@line = 0 def Sup.Ctest @@line += 1 @@x += @@x[0,1] print @@line, "-", @@x, "\n" end end Sup.Ctest # first test Sup.Ctest # second test class Sub1 < Sup # define subclass @@x = "B" end Sub1.Ctest # third test Sup.Ctest # fourth test # - - - - end This produces: 1-AA 2-AAA 3-BB 4-BBB I am not sure if that really helps you with the question you're asking, though. Note that since you are only using class variables for this example, we can simply use a class method. There is no need for creating any instances of either of these classes, as far as the class variables are concerned. To get back to why there would be only one @@x for a class and all it's subclasses, let me refer to a line from the "Programming Ruby" (pickaxe) book: "A class variable is shared among all objects of a class, and is also accessible to the class methods...". Any object which is an instance of 'Sub1' is also, by definition, an instance of 'Sup'. If a class variable is shared among *all* objects of class 'Sup', then the exact same variable must also be shared with the objects which happen to be from class 'Sub1'. -- Garance Alistair Drosehn = gad@gilead.netel.rpi.edu Senior Systems Programmer or gad@freebsd.org Rensselaer Polytechnic Institute or drosih@rpi.edu