I would like to merge a nested hash.
a = {:book=>
[{:title=>\"Hamlet\",
:author=>\"William Shakespeare\"
}]}
b = {:book=>
[{
For variety's sake - and this will only work if you want to merge all the keys in your hash in the same way - you could do this:
a.merge(b) { |k, x, y| x + y }
When you pass a block to Hash#merge
, k
is the key being merged, where the key exists in both a
and b
, x
is the value of a[k]
and y
is the value of b[k]
. The result of the block becomes the value in the merged hash for key k
.
I think in your specific case though, nkm's answer is better.