You can use the #send method to call an object method by the method name:
object.send(:foo) # same as object.foo
You can pass arguments when calling a method:
object.send(:foo, 1, "bar", 1.23) # same as object.foo(1, "bar", 1.23)
So, if you have the attribute name in the variable "attribute", you can read the attribute of the object with
object.send(attribute.to_sym)
and write the attribute value with
object.send("#{attribute}=".to_sym, value)
In Ruby 1.8.6, the #send method can execute any method of an object, regardless of its visibility (you can, for example, call private methods). This may be changed in future versions of Ruby, and you should not rely on it. To execute private methods, use #instance_eval:
object.instance_eval { # code as block, can reference variables in current scope } # or object.instance_eval <<-CODE # code as string, can generate any code text CODE
Update
You can use public_send to call methods regarding visibility rules.
object.public_send :public_foo # ok object.public_send :private_bar # exception
Maxim Kulkin Nov 19 '08 at 13:14 2008-11-19 13:14
source share