我可以创建一个块,将哈希元素提取并转换为本地变量,但我想知道是否已经存在原生方法。类似于这样的东西:
extract({ :foo => 'bar', :foo2 => 'bar2' })
puts foo # 'bar'
puts foo2 # 'bar2'
请注意,这些密钥是私有的,作用域需要保持本地化。
bar, bar2 = h.values_at :foo, :foo2
或者我们可以扩展Hash以提取实例变量:
class Hash
def extract o
each { |k, v| o.instance_variable_set '@' + k.to_s, v }
end
end
h.extract self
p [@foo, @foo2]
您可以使用each
方法遍历每个key=>value
对:
{ :foo => 'bar', :foo2 => 'bar2' }.each do |key, value|
print key,"\t",value,"\n"
end
输出:
foo bar
foo2 bar2