From: Robert Dober Date: 2007-05-03T13:56:47+09:00 Subject: Re: simple subclass question On 5/3/07, Gary Wright wrote: > > On May 2, 2007, at 2:57 PM, Ball, Donald A Jr (Library) wrote: > > In the superclass, I want a chunk of code that > > initializes a class instance variable in itself and each of its class > > descendents. > > You can use #inherited to trigger your own class initialization: > > class Base > class < def inherited(other) > other.instance_eval { initialize_class } > end > def initialize_class > @foo = 42 > end > attr_accessor :foo > end > initialize_class > end > > class Subclass < Base > puts "foo is #{@foo}" # 42 > end > > puts Subclass.foo # 42 > puts Class.new(Base).foo # 42 > > > > Gary Wright Wow that scales much better than mine Gary, nice. However maybe you want to inherit @foo dynamically, that is I suggest this slight adaptation of Base 529/29 > cat inherited.rb && ruby inherited.rb # vim: sts=2 sw=2 expandtab tw=0 nu: class Base @foo = 42 class <