动态设置 Ruby 对象的属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7849521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:24:46  来源:igfitidea点击:

Set Attribute Dynamically of Ruby Object

rubydynamic

提问by neebz

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

如何在 Ruby 中动态设置对象属性,例如

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

回答by lucapette

Use send:

使用发送

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

回答by Jochem Schulenklopper

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

Object#instance_variable_set()是您正在寻找的,并且是您想要的更干净的版本。

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

Ruby 文档关于 Object#instance_variable_set

回答by Benjineer

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

回答by Tincho Rockss

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

这个答案(https://stackoverflow.com/a/7466385/6094965)对我有用:

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

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

attribute必须是一个String. 因此,如果您正在遍历Symbols数组(像我一样),则可以使用to_s.

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