Set Attribute Dynamically of Ruby Object

后端 未结 4 838
一向
一向 2020-12-05 12:49

How can I set an object attribute dynamically in Ruby e.g.

def set_property(obj, prop_name, prop_value)
    #need to do something like > obj.prop_name =          


        
4条回答
  •  离开以前
    2020-12-05 13:16

    This answer (https://stackoverflow.com/a/7466385/6094965) worked for me:

    Object.send(attribute + '=', value)
    

    attribute has to be a String. So if you are iterating trough an array of Symbols (like me), you can use to_s.

    Object.send(attribute.to_s + '=', value) 
    

提交回复
热议问题