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 B. 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,

Marnen Laibow-Koser
http://www.marnen.org
[email protected]

Sent from my iPhone

On 9 December 2010 06:09, Priya B. [email protected] wrote:

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

use “merge”… class Hash - RDoc Documentation

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}

On Dec 9, 2010, at 7:09 AM, Vladimir R. wrote:

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.

irb> Hash[*array_of_hashes.map{||.to_a}.flatten]
=> {:second=>2, :third=>3, :first=>10}

-Rob

Rob B.
[email protected] http://AgileConsultingLLC.com/
[email protected] 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)

On Thu, Dec 9, 2010 at 9:18 AM, Marnen Laibow-Koser

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