From: "Jesús Gabriel y Galán" Date: 2011-02-07T17:57:09+09:00 Subject: Re: Setter method for Hash value On Sun, Feb 6, 2011 at 10:23 PM, Rolf Pedersen wrote: > 2011/2/4 Jesús Gabriel y Galán > >> For the other two, you need a proxy object that can delegate [] and >> []= to DataClass too. For this to work, MyClass#props needs to wrap >> the actual hash returned by DataClass with a wrapper object (Props). >> As you need this proxy object to have some hash like behaviour, you >> can implement whatever methods you need to behave like a hash. As an >> example, apart from [] and []= I have implemented inspect and to_s. >> >> > Instead of implementing other methods to make the wrapper object behave more > like a Hash object, why not let Props inherit Hash, and just redefine those > methods that I need to behave differently? Perhaps like this: > > class Props < Hash >  def initialize h >    replace h >  end >  def [](key) >    ... >  end >  def []=(key, value) >    ... >  end > end Hi, In fact I was going to follow up the discussion with a further idea. What I sent has a flaw, and it's the fact that the Props object gets initialized with the hash, while ideally it should delegate also all reads to the DataClass. It doesn't make sense to have a reference to the resulting hash. This way, if the hash in DataClass is modified by other means, the new values will be available to all instances of Props (in the current implementation this might be true, because we are returning references to the same hash, but this can be a weak point). It's cleaner this way, in my opinion: class MyClass def props Props.new end def props=(h) DataClass::set_props h end end class Props def [](key) DataClass::get_prop key end def []=(key,value) DataClass::set_prop key,value end def inspect; DataClass::get_props.inspect; end def to_s; DataClass::get_props.to_s; end end class DataClass @data = {:a=>1, :b=>2, :c=>3} def self.get_props() @data end def self.get_prop(key) @data[key] end def self.set_props(data) @data = data end def self.set_prop(key, value) @data[key] = value end end As for your question about inheriting from Hash: read a bit about Inheritance vs Composition. It's generally considered that Composition is more flexible. Jesus.