From: "Jesús Gabriel y Galán" Date: 2011-02-05T03:16:51+09:00 Subject: Re: Setter method for Hash value On Fri, Feb 4, 2011 at 5:03 PM, Rolf Pedersen wrote: > Hi Jesus > > It does seem to be working. At least the example "requirements" that I > defined does give the expected response. > I have to admit, I need to study this a bit, to figure out HOW it is > working, though. ;o) You have two sets of requirements: 1.- Calls on the instance of MyClass: props and props= 2.- Calls on the object returned by the previous props calls: [] and []= You need to forward these 4 calls to another class. The first two are easy: we just implement the MyClass#props and MyClass#props= to do what we want. 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. On Fri, Feb 4, 2011 at 3:45 PM, Brian Candler wrote: > Try to avoid class variables. An instance variable of the class (@data) > would work just as well here. @@var has really strange semantics which I > can never entirely remember, and once you've been bitten by them, you'll > choose to use instance variables as well. I completely agree. I was in a rush when I wrote my previous post, so I left it as it is. Using instance variables on the DataClass object is cleaner: irb(main):030:0> class DataClass irb(main):031:1> @data = {:a=>1, :b=>2, :c=>3} irb(main):032:1> def self.get_props() irb(main):033:2> @data irb(main):034:2> end irb(main):035:1> def self.get_prop(key) irb(main):036:2> @data[key] irb(main):037:2> end irb(main):038:1> def self.set_props(data) irb(main):039:2> @data = data irb(main):040:2> end irb(main):041:1> def self.set_prop(key, value) irb(main):042:2> @data[key] = value irb(main):043:2> end irb(main):044:1> end => nil irb(main):045:0> c = MyClass.new => # irb(main):046:0> c.props => {:b=>2, :a=>1, :c=>3} irb(main):047:0> c.props = {:a => 3, :b => 0, :c => 5, :d => 6} => {:b=>0, :a=>3, :c=>5, :d=>6} irb(main):048:0> c.props => {:b=>0, :a=>3, :c=>5, :d=>6} irb(main):049:0> c.props[:a] => 3 irb(main):050:0> c.props[:a] = 55 => 55 irb(main):051:0> c.props[:a] => 55 irb(main):052:0> c.props => {:b=>0, :a=>55, :c=>5, :d=>6} I hope it's clearer now. Let me know if you need further help understanding this. Jesus.