Set Attribute Dynamically of Ruby Object

RubyDynamic

Ruby Problem Overview


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 = prop_value 

    #we can use eval but I'll prefer a faster/cleaner alternative:
    eval "obj.#{prop_name} = #{prop_value}"
end

Ruby Solutions


Solution 1 - Ruby

Use send:

def set_property(obj, prop_name, prop_value)
    obj.send("#{prop_name}=",prop_value)
end

Solution 2 - Ruby

Object#instance_variable_set() is what you are looking for, and is the cleaner version of what you wanted.

Example:

your_object = Object.new
your_object.instance_variable_set(:@attribute, 'value')
your_object
# => <Object:0x007fabda110408 @attribute="value">

Ruby documentation about Object#instance_variable_set

Solution 3 - Ruby

If circumstances allow for an instance method, the following is not overly offensive:

class P00t
  attr_reader :w00t

  def set_property(name, value)
    prop_name = "@#{name}".to_sym # you need the property name, prefixed with a '@', as a symbol
    self.instance_variable_set(prop_name, value)
  end
end

Usage:

p = P00t.new
p.set_property('w00t', 'jeremy')

Solution 4 - Ruby

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) 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionneebzView Question on Stackoverflow
Solution 1 - RubylucapetteView Answer on Stackoverflow
Solution 2 - RubyJochem SchulenklopperView Answer on Stackoverflow
Solution 3 - RubyBenjineerView Answer on Stackoverflow
Solution 4 - RubyTincho RockssView Answer on Stackoverflow