Ruby元编程:动态实例变量名称 [英] Ruby Metaprogramming: dynamic instance variable names
本文介绍了Ruby元编程:动态实例变量名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下哈希值:
{ :foo => 'bar', :baz => 'qux' }
如何动态设置键和值以使其成为对象中的实例变量...
How could I dynamically set the keys and values to become instance variables in an object...
class Example
def initialize( hash )
... magic happens here...
end
end
...这样我就可以在模型中得到以下内容...
... so that I end up with the following inside the model...
@foo = 'bar'
@baz = 'qux'
?
推荐答案
The method you are looking for is instance_variable_set
. So:
hash.each { |name, value| instance_variable_set(name, value) }
或更简单地说,
hash.each &method(:instance_variable_set)
如果您的实例变量名称缺少"@"(例如在OP的示例中),则需要添加它们,因此更像是:
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) }
这篇关于Ruby元编程:动态实例变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文