Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby equivalent of Python setattr()

Tags:

ruby

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.

like image 209
JohnMetta Avatar asked Jan 25 '10 23:01

JohnMetta


1 Answers

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).

like image 198
sepp2k Avatar answered Sep 21 '22 17:09

sepp2k