Is there a Ruby equivalent for a PHP extract?

I can create a block that will extract the hash elements and turn them into local variables, but I wonder if there is a native method. Something like that:

extract({ :foo => 'bar', :foo2 => 'bar2' }) puts foo # 'bar' puts foo2 # 'bar2' 

Note that the keys are private and that the scope must remain local.

+6
source share
2 answers

You can get closer:

 bar, bar2 = h.values_at :foo, :foo2 

Or, I assume that we could extend the 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] 
+7
source

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

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

Outputs:

  foo bar foo2 bar2 
+1
source

Source: https://habr.com/ru/post/891031/


All Articles