有没有一个相当于PHP的提取的Ruby? [英] Is there a Ruby equivalent to PHP's extract?
本文介绍了有没有一个相当于PHP的提取的Ruby?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以创建一个块来提取散列元素并将它们变成局部变量,但是我想知道是否已经存在本地方法。像这样:
extract({:foo =>'bar',:foo2 =>'bar2'})
puts foo#'bar'
puts foo2#'bar2'
注密钥是私密的,并且范围需要保持在本地。
解决方案
您可以关闭:
bar,bar2 = h.values_at:foo,:foo2
或者我想我们可以扩展Hash以提取实例变量:
$ p $ class Hash
def提取o
each {| k,v | o.instance_variable_set'@'+ k.to_s,v}
end
end
h.extract self
p [@foo,@ foo2]
I can create a block that will extract hash elements and turn them into local variables, but I'm wondering if a native method already exists. Something like this:
extract({ :foo => 'bar', :foo2 => 'bar2' })
puts foo # 'bar'
puts foo2 # 'bar2'
Note that the keys are private, and that the scope needs to stay local.
解决方案
You can get close:
bar, bar2 = h.values_at :foo, :foo2
Or I suppose we could extend Hash to extract into instance variables:
class Hash
def extract o
each { |k, v| o.instance_variable_set '@' + k.to_s, v }
end
end
h.extract self
p [@foo, @foo2]
这篇关于有没有一个相当于PHP的提取的Ruby?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文