user1320651
user1320651

Reputation: 836

Transforming a hash object in ruby

Curious to know the best way to do this in ruby. I have done it but think Im not doing the best

I have a hash object as follows

{2=>{:name=>"Somename"}, 3=>{:last_name=>"Something"}}

I want to get to

{:name=>"Somename",:last_name=>"Something"}

Upvotes: 0

Views: 97

Answers (2)

megas
megas

Reputation: 21791

input_hash.values.reduce { |h,v| h.merge(v) }

UPDATE: I thought that my answer is shortest but I was wrong, the answer from tokland:

input_hash.values.reduce(:merge)

Upvotes: 5

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84353

Use the Splat Operator

In this particular case, you can extract the values of your hash into an array of hashes with the splat operator. For example:

my_hash = {2=>{:name=>"Somename"}, 3=>{:last_name=>"Something"}}
[*my_hash.values]
# => [{:name=>"Somename"}, {:last_name=>"Something"}]

Upvotes: 1

Related Questions