Ruby: merge nested hash

前端 未结 9 1854
渐次进展
渐次进展 2020-11-30 06:25

I would like to merge a nested hash.

a = {:book=>
    [{:title=>\"Hamlet\",
      :author=>\"William Shakespeare\"
      }]}

b = {:book=>
    [{         


        
9条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 06:51

    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.

提交回复
热议问题