tags:

views:

134

answers:

1

Well, add me to the list of Python programmers who are falling in love with Ruby but have a lingering PyAddiction. Like the post about Python's getattr, I'm looking for the Ruby equivalent of doing this:

setattr(obj, 'attribute', value)

where obj is an object instance, attribute is the name of one of the object's attributes as a string, and value is the value of that object. The equivalent code being:

obj.attribute = value

I'm assuming it's possible (because anything possible in Python seems even easier in Ruby now), but can't find documentation of it.

+10  A: 

Either obj.instance_variable_set("@instance_variable", value) or obj.send("instance_variable=", value).

The former directly sets the instance variable. The latter calls the setter method, which of course only works if there is a setter method, but on the other hand also works if you have a setter method that doesn't actually only set an instance variable (or doesn't set an instance variable at all).

sepp2k
NB: the first parameter to `instance_variable_set` and `send` may also be symbols
banister