Array of Hashes into single Hash in Ruby

Something I always use so much! We all do have usecases where we land up having Array of Hashes and we want to merge it into one single Hash in Ruby, right? Pretty in Ruby to do that.

Lets take an example

a_hash=[{"key1"=>"value1"},{"key2"=>"value2"},{"key3"=>"value3"},{"key4"=>nil}]

Resule we want is something like this final_hash = {“key1″=>”value1”, “key2″=>”value2″,”key3″=>”value3”, “key4″=>nil}

Well here’s the snippet

final_hash = Hash[*a_hash.collect{|h| h.to_a}.flatten]

and final_hash becomes {“key4″=>nil, “key3″=>”value3”, “key2″=>”value2”, “key1″=>”value1”}, exactly what we wanted!

Let’s break this into parts and see what’s going on.

a_hash.collect{|h| h.to_a} gives me [[[“key1”, “value1”]], [[“key2”, “value2”]], [[“key3”, “value3”]], [[“key4”, nil]]]

For every a_hash element which is a Hash in itself we are first converting it to an array with two elements first is key and followed by value.

a_hash.collect{|h| h.to_a}.flatten => [“key1”, “value1”, “key2”, “value2”, “key3”, “value3”, “key4”, nil] flattens the whole set into a single Array.

Last is left for simple Hash to construction! Simple! Hash[“key1”, “value1”, “key2”, “value2”, “key3”, “value3”, “key4”, nil], We are done!

What if you wanted to remove the keys with nil values?

final_hash = Hash[*a_hash.collect{|h| h.to_a}.flatten].delete_if{|k,v| v.blank?}

FInally a delete_if value is blank on the final Hash deletes any key for which value is nil or “”! Pretty simple na.

2 thoughts on “Array of Hashes into single Hash in Ruby

Leave a comment