From: David Alan Black Date: 2001-08-11T11:54:28+09:00 Subject: [ruby-talk:19512] Re: the way class variables work Hello -- On Sat, 11 Aug 2001, Jim Menard wrote: > David Alan Black writes: > > > Hello -- > > > > I've been puzzling over Ruby's treatment of class variables -- not so > > much the "what" as the "why". > > > > It seems strange to me that a class somewhere off in one side of an > > inheritance tree can affect a class variable all over the tree. [...] > > Class variables seem to be not so much per class as per class > > hierarchy or family. I can't quite figure out why they work this way, > > rather than working like instance methods (so that redefinition in a > > child class stops the search process up the inheritance path). > > Let me try. The key is that classes are objects too, and they have their > own inheritance tree, complete with methods and instance variables > (attributes). > > Vehicle ----------- Vehicle class (with attr @@tires) > | \ | \ > Car Bike -------- Car class Bike class > > In this case, the object that represents the Vehicle class has an instance > variable called 'tires'. That instance variable exists in the Vehicle class > object. > > The line "@@tires = 0" creates a new instance variable inside the Vehicle > class object. The lines "@@tires = 4" and "@@tiers = 2" assign new values > to that instance variable, they don't declare new instances. But creating a new class does create a new instance of class Class. So if class variables can be understood as instance variables of instances of class Class, then in this example: class A @@cv = 123 end class B < A end where we have two instances of class Class, each instance should (in my opinion) have its own copies of its instance variables, and changing B's @@cv should not affect A's @@cv. That would conform to how instance variables work elsewhere. Even though class B is a child of class A, it should have as much "right" to its own instance variables as class A has. A and B are both, equally, instances of class Class. Their parent/child relationship is irrelevant to this. That relationship *is* relevant to how things are searched for. OK... so in the cases of class methods, instance methods, constants, and embedded class and module definitions, the way it works is: the child class can override or redefine the thing, but if it doesn't, the parent class's version (if any) will be used. Class variables work completely differently. The child class *cannot* say, "Thank you very much, Parent, but I'm going to do my own version of that." That's why I find class variables anomalous. Also, can it really be good, from the point of view of code maintenance, for a child class to have the power to change its parent, and all of that parent's other children, including future ones? Doesn't that make things very unstable? David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav