Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to remap a Hash in Ruby?

Tags:

ruby

hash

remap

Is there a simple way of remapping a hash in ruby the following way:

from:

{:name => "foo", :value => "bar"}

to:

{"foo" => "bar"}

Preferably in a way that makes it simple to do this operation while iterating over an array of this type of hashes:

from:

[{:name => "foo", :value => "bar"}, {:name => "foo2", :value => "bar2"}]

to:

{"foo" => "bar", "foo2" => "bar2"}

Thanks.

like image 927
Fredrik Boström Avatar asked Dec 10 '22 21:12

Fredrik Boström


1 Answers

arr = [ {:name=>"foo", :value=>"bar"}, {:name=>"foo2", :value=>"bar2"}]

result = {}
arr.each{|x| result[x[:name]] = x[:value]}

# result is now {"foo2"=>"bar2", "foo"=>"bar"}
like image 86
Gishu Avatar answered Jan 01 '23 10:01

Gishu