From: Robert Klemme Date: 2010-10-31T21:40:13+09:00 Subject: Re: Dynamically reference instance vars On 30.10.2010 22:11, Greg Willits wrote: > Ryan Davis wrote in post #958245: >> On Oct 30, 2010, at 12:27 , Greg Willits wrote: >> >>> I was hoping in Ruby that at least this was possible: >>> >>> myobject.send(iname) = ivalue >>> --or-- >>> myobject.send(iname, ivalue) >> >> You're confusing methods and variables. They're not the same, but you're >> on the right track with the code above, but you'd be calling the getter, >> not the setter. Check it: >> >> class X >> attr_accessor :x # creates x and x= methods >> end >> >> o = X.new >> o.send("x=", 42) >> p x > > I wasn't confusing them, I was hoping Ruby's send would be flexible > enough to work with both of them (in conjunction with the accessors > being defined). What I didn't think of in this context was Ruby's x= > being considered the setter method and not just x, which I knew, and > should have recognized -- so yep, that was the ticket. You win! :-) > Sorry, no prizes :-( Here are two other approaches using widely underused class Struct and that differ in the way they deal with values not present in the Hash: Shape = Struct.new :size, :fill_color, :line_color, :line_width do def self.from_hash_1(h) sh = new h.each {|k,v| sh[k] = v} sh end def self.from_hash_2(h) sh = new members.each {|m| sh[m] = h[m]} sh end end irb(main):015:0* s1 = Shape.from_hash_1( irb(main):016:1* :size => 'small', irb(main):017:1* :fill_color => 'red', irb(main):018:1* :line_color => 'black', irb(main):019:1* :line_width => '2' irb(main):020:1> ) => # irb(main):021:0> s2 = Shape.from_hash_2( irb(main):022:1* :size => 'small', irb(main):023:1* :fill_color => 'red', irb(main):024:1* :line_color => 'black', irb(main):025:1* :line_width => '2' irb(main):026:1> ) => # If you like that better you can as well define def Shape(h) sh = Shape.new # logic from above sh end Then you can do s1 = Shape( :size => 'small', :fill_color => 'red', :line_color => 'black', :line_width => '2' ) Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/