From: "Gray, Jeff" Date: 2002-07-03T07:37:40+09:00 Subject: Treatment of class variables in inherited classes This question probably has more to do with the fundamentals of OOP than Ruby specifically, but I'm looking for an explanation of why the behavior of class variables in inherited classes is the way it is. Consider: --- class Box # @@stuff = {:e => 1} # intentionally commented out def Box.add(k, v) @@stuff[k] = v end def Box.[](knobname) @@stuff[knobname] end end class Crate < Box @@stuff = {:e => 2} end class Suitcase < Box @@stuff = {:e => 3} end Crate.add(:d, 4) Suitcase.add(:d, 5) puts Crate[:d] # -> 4 [would be 5 if line 2 were uncommented] puts Suitcase[:d] # -> 5 puts Crate[:e] # -> 2 [would be 3 if line 2 were uncommented] --- So when a class variable is defined in a parent class, all inherited classes see the same object. More specifically, the most recent definition of that class variable is used, even if it occurred in a subclass. Yet when a class variable is not initialized in the parent class, the variable points to different objects in each class. This is sensible, but it feels like there is lacking a "have your cake and eat it too" mechanism that allows for inherited classes to override/redefine class variables without affecting the ancestor and sibling classes. So what are the guiding principles of inheritance that account for this behavior? Thanks, - jeff