merge some complex hashes in ruby

岁酱吖の 提交于 2019-12-07 17:20:35

问题


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.


回答1:


This should work for you:

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


来源:https://stackoverflow.com/questions/10691318/merge-some-complex-hashes-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!