From: jweirich@... Date: 2001-08-11T21:49:17+09:00 Subject: [ruby-talk:19525] Re: the way class variables work >>>>> "David" == David Alan Black writes: David> I've been puzzling over Ruby's treatment of class variables David> -- not so much the "what" as the "why". [... example elided ...] David> Class variables seem to be not so much per class as per David> class hierarchy or family. I can't quite figure out why David> they work this way, rather than working like instance David> methods (so that redefinition in a child class stops the David> search process up the inheritance path). David> Insights, opinions, and/or words of wisdom welcome. In Smalltalk, there are two kinds of "class" variables. There are class variables which work the way Ruby class variables work (shared across an inheritance hierarchy). But there are also class *instance* variables which are unique to the individual class object (instance) where they are defined. It turns out that both types of class variables are supported in Ruby as well... class A class << self def class_instance_var @class_instance_var end def class_var @@class_var end end @@class_var = 0 # Shared across hierarchy @class_instance_var = 10 # Unique to class end class B < A @@class_var = 1 # Shared @class_instance_var = 11 # Unique end puts A.class_var # => 1 puts B.class_var # => 1 puts A.class_instance_var # => 10 puts B.class_instance_var # => 11 Class variable mimic "static" variables in Java or C++. Class instance variables are instance variables in the class object. I hope this helps. -- -- Jim Weirich jweirich@one.net http://w3.one.net/~jweirich --------------------------------------------------------------------- "Beware of bugs in the above code; I have only proved it correct, not tried it." -- Donald Knuth (in a memo to Peter van Emde Boas)