有没有Ruby相当于PHP的提取?
我可以创建一个块来提取哈希元素并将它们转换为局部变量,但我想知道原始方法是否已经存在。 像这样的东西:
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