From: ara.t.howard@... Date: 2007-03-28T08:27:01+09:00 Subject: Re: dynamically adding class variables On Wed, 28 Mar 2007, Siemen Baader wrote: > > Could anyone enlighten me on why class_variables finds the class variable in > the subclass and why the class methods act like they were invoked on the > parent class? Apparently class_variables finds the variables in a different > way than ruby does when it evaluates the method code... @@vars are shared among all child classes. @var belong to only one class even though methods which access them might be inherited - in otherwords you must initialize them in each child. ruby provides not built-in way to do this. > Also, has anyone a good idea how I can give each child class variables which > are shared among all instances of the classes but isolated from parents and > other children? traits and attributes both solve this problem completely. traits.rb is a bit heavy-weight and offers many other features. attributes.rb is only 42 lines of code but solves the issue you are dealing with. i reccomend using attributes.rb # gem install attributes http://codeforpeople.com/lib/ruby/attributes/attributes-3.2.0/README to use with classes just do class Base class << self attribute(:a){ 42 } end end class Derived < Base end the will setup both classes so that the default value of 'a' is 42 and it is not shared, but it can be overriden easily too Derived.a = 42.0 traits info # gem install trails http://codeforpeople.com/lib/ruby/traits/traits-0.9.2/README regards. -a -- be kind whenever possible... it is always possible. - the dalai lama