Thursday, January 16, 2014

Ruby, turn array of hashes into single hash

I have the following Array of Hashes:

a = [{:a => 1, :b => "x"}, {:a => 2, :b => "y"}]

I need to turn it into:

z={"x" => 1, "y" => 2} 

or:

z={1 => "x", 2 => "y"}

Can I do this in a clean & functional way?

Something like this:

Hash[a.map(&:values)] # => {1=>"x", 2=>"y"}

if you want the other way:

Hash[a.map(&:values).map(&:reverse)] # => {"x"=>1, "y"=>2}

incorporating the suggestion from @squiguy:

Hash[a.map(&:values)].invert

No comments:

Post a Comment