Is there a Ruby equivalent to PHP's extract?

谁都会走 提交于 2019-12-01 16:34:39

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]

You can use the each method to iterate through each key=>value pair:

{ :foo => 'bar', :foo2 => 'bar2' }.each do |key, value|
  print key,"\t",value,"\n"
end

Outputs:

 foo     bar
 foo2    bar2
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!