On Thu, 23 Nov 2006, Joel VanderWerf wrote:

<snip smart code>
>
>  mc = MyClass.new
>
>  mc.push_something 3
>  p mc # ==> #<MyClass:0xb7d65a7c @something_list=[3]>
>
> Getting this to work for subclasses as well is left as an exercise to the 
> reader ;)

to do exactly this, without any extract class instance vars, plus proper
behaviour in subclasses, and not too many extract singletons, one can simply
use attributes.rb (from the metakoans.rb rubyquiz):

     harp:~ > cat a.rb
     require 'set'
     require 'rubygems'
     require 'attributes' ### gem install attributes - it's __only__ 42 lines!

     class C
       attribute('array'){ Array.new }
       attribute('set'){ Set.new }

       def initialize
         self.class.attributes.each{|a| send a} # force init
       end

       def array_push(obj) @array << obj end
       def set_push(obj) @set << obj end
     end

     class B < C; end


     #
     # works for objects
     #
       c = C.new
       c.array_push 42
       c.set_push 42
       p c.array
       p c.set

     #
     # even in subclasses
     #
       b = B.new
       p b.array
       p b.set


     harp:~ > ruby a.rb
     [42]
     #<Set: {42}>
     []
     #<Set: {}>


if you hate installing/depending-on gems then just steal the code: it's so
short you can inline it!


regards.

-a
-- 
my religion is very simple.  my religion is kindness. -- the dalai lama