1

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 and functional way?

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

You can just use invert for the bottom example, since it will handle duplicate keys, but +1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.