开发者

Is there a Ruby equivalent to PHP's extract?

开发者_如何转开发

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]


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜