From: Tony Arcieri Date: 2010-10-31T04:49:20+09:00 Subject: Re: Dynamically reference instance vars --001636c5b1e1dec3470493dade67 Content-Type: text/plain; charset=ISO-8859-1 On Sat, Oct 30, 2010 at 1:27 PM, Greg Willits wrote: > The question is whether there's a shorter way to do this: > > my_object.send(:instance_variable_set, "@#{iname}", ivalue) > > In another language I used, I could simply do the equivalent of > > myobject.iname = ivalue > This breaks the encapsulation that objects are supposed to provide for their hidden state. I have to say I *like* the fact that instance_variable_get/instance_variable_set are long and unwieldy. By using them you hopefully remind yourself that you're doing something naughty by touching an object's private parts. > I was hoping in Ruby that at least this was possible: > > myobject.send(iname) = ivalue > --or-- > myobject.send(iname, ivalue) > > but that doesn't work. I could maybe force it to work by manually > creating setter methods, but that's not an elegant solution either, I'd > rather have the occassional use of instance_variable_set than craft > setters. It's Ruby, a lot is possible! You could add some method_missing magic so: myobj.iv_foobar = 42 thunks to: instance_variable_set(:@foobar, 42) I would strongly recommend against that sort of thing though. -- Tony Arcieri Medioh! A Kudelski Brand --001636c5b1e1dec3470493dade67--