Merging multiple hashes as single hash

Hi All,

I'm having unknown number of hashes. How to merge all those hashes into
single hash?

Thanks,
Buvana

Priya Buvan wrote in post #967340:

Hi All,

I'm having unknown number of hashes. How to merge all those hashes into
single hash?

Think about the semantics here! What happens if the same key appears in
all the hashes? Which value takes priority?

You can use inject to merge the hashes, but you probably won't get the
desired result.

Thanks,
Buvana

Best,

use "merge"... http://ruby-doc.org/core/classes/Hash.html#M002880

When you say you have "unknown number", are they in an array? if so,
iterate it an merge them...

@Michael: yes its in array..

@Marnen: If there is more than one key with same name, obviously it'll
be override. This is fine.

Anyway i'm trying to fetch the result separately. I'll reply with latest
updated soon.

Thanks,
Buvana

array_of_hashes = [{:first => 1, :second => 2}, {:first => 10, :third => 3}]

Hash[*array_of_hashes.collect{|hash| hash.collect{|key,value|
[key,value].flatten}.flatten}.flatten]
=> {:first=>10, :second=>2, :third=>3}

array_of_hashes = [{:first => 1, :second => 2}, {:first => 10, :third => 3}]

Hash[*array_of_hashes.collect{|hash| hash.collect{|key,value|
[key,value].flatten}.flatten}.flatten]
=> {:first=>10, :second=>2, :third=>3}

Simpler, but same idea.

Hash[*array_of_hashes.map{|_|_.to_a}.flatten]

=> {:second=>2, :third=>3, :first=>10}

-Rob

Rob Biedenharn
Rob@AgileConsultingLLC.com http://AgileConsultingLLC.com/
rab@GaslightSoftware.com http://GaslightSoftware.com/

You can use inject to merge the hashes, but you probably won't get the
desired result.

Actually, looks like you get the desired result

a = [{:first => 1, :second => 2}, {:first => 10, :third => 3}]
a.inject(:merge)

In case you need something more smart in the future to deal with same
keys in hashes:

http://rubyworks.github.com/facets/doc/api/core/Hash.html#method-i-weave

Robert Pankowecki
http://robert.pankowecki.pl