3

I'd like to merge the following hashes together.

 h1 = {"201201" => {:received => 2},   "201202" => {:received => 4 }}
 h2 = {"201201" => {:closed => 1},  "201202" => {:closed => 1 }}

particularly, my expected result is:

h1 = {"201201" => {:received => 2, :closed => 1},  "201202" => {:received => 4, :closed => 1 }}

I have tried every way as:

h = h1.merge(h2){|key, first, second| {first , second} }

unfortunately, neither seemed to work out fine for me. any advice would be really appreciated.

Sarun Sermsuwan
  • 3,608
  • 5
  • 34
  • 46

1 Answers1

6

This should work for you:

h = h1.merge(h2){|key, first, second| first.merge(second)}
Hck
  • 9,087
  • 2
  • 30
  • 25
  • 2
    Ah, the block form of [`Hash#merge`](http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-merge) is such a beautiful thing. – Phrogz May 21 '12 at 20:01
  • 2
    If you wanted recursive merging: `m=->(k,a,b){ a.merge(b,&m) }; h = m[nil,h1,h2]` – Phrogz May 21 '12 at 20:02