"Florian Weber" <csshsh / structbench.com> schrieb im Newsbeitrag
news:1A38E5B7-C83D-11D8-B166-000A95BD142E / structbench.com...
> hi!
>
> im having two classes.. fruit and apple.
>
> i wanna do something like
>
> class Apple < Fruit
>     add_something "foobar"
> end
>
> in the fruit class i have a add_something method
> which i want to save the "foobar" to a static hash
> in the apple class. the hash however should also
> not be declared in the apple class.
>
> is this somehow possible? i guess not, or? just

It is:

class Fruit
  def self.inherited(sub_class)
    def sub_class.add_something(some, thing=true)
      @somethings[some] = thing
    end

    sub_class.instance_eval { @somethings = {} }

    # test code:
    p sub_class
    def sub_class.somethings; @somethings; end
  end
end

class Apple < Fruit
  add_something "foo"
end

p Apple.somethings

> making sure, since ruby definitely has a lot of suprises =)
>
> i guess the only other way would be to make a static
> hash in the fruit class which is 2d, the first dimension being
> the subclass..

Yeah, that's the other option.  However, I guess storing it in the class
itself is better for performance and GC reasons.

Regards

    robert