I have the following code:
for attribute in site.device_attributes device.attribute end
where I would like the code to substitute the value of ‘attribute’ for the method name.
I have tried device.'#{attribute}' and various permutations.
Is this completely impossible? Am I missing something?
I have considered overriding method_missing, but I can’t figure out how that would actually help me when my problem is that I need to call an ‘unknown’ method.
You can use #send method to call object’s method by method’s name:
You can pass arguments with to invoked method:
So, if you have attribute name in variable ‘attribute’ you can read object’s attribute with
and write attribute’s value with
In Ruby 1.8.6 #send method can execute any object’s method regardless of its visibility (you can e.g. call private methods). This is subject to change in future versions of Ruby and you shouldn’t rely on it. To execute private methods, use #instance_eval:
Update
You can use
public_sendto call methods with regard to visibility rules.