Ruby Metaprogramming: dynamic instance variable names

断了今生、忘了曾经 提交于 2019-11-28 15:41:32
Chuck

The method you are looking for is instance_variable_set. So:

hash.each { |name, value| instance_variable_set(name, value) }

Or, more briefly,

hash.each &method(:instance_variable_set)

If your instance variable names are missing the "@" (as they are in the OP's example), you'll need to add them, so it would be more like:

hash.each { |name, value| instance_variable_set("@#{name}", value) }
h = { :foo => 'bar', :baz => 'qux' }

o = Struct.new(*h.keys).new(*h.values)

o.baz
 => "qux" 
o.foo
 => "bar" 

You make we want to cry :)

In any case, see Object#instance_variable_get and Object#instance_variable_set.

Happy coding.

You can also use send which prevents the user from setting non-existent instance variables:

def initialize(hash)
  hash.each { |key, value| send("#{key}=", value) }
end

Use send when in your class there is a setter like attr_accessor for your instance variables:

class Example
  attr_accessor :foo, :baz
  def initialize(hash)
    hash.each { |key, value| send("#{key}=", value) }
  end
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!