Ruby:合并嵌套散列 [英] Ruby: merge nested hash

查看:130
本文介绍了Ruby:合并嵌套散列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

b = {:book =>
[{:title =>Pride and Prejudice,
:author =>Jane Austen
}]}
pre>

我希望合并为:

  {:书=> 
[{:title =>Hamlet,
:author =>William Shakespeare},
{:title =>傲慢与偏见,
:author =>Jane Austen}]}


解决方案

对于rails 3.0.0+或更高版本,有 deep_merge 功能,用于 ActiveSupport ,它完全符合您的要求。


I would like to merge a nested hash.

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

b = {:book=>
    [{:title=>"Pride and Prejudice",
      :author=>"Jane Austen"
      }]}

I would like the merge to be:

{:book=>
   [{:title=>"Hamlet",
      :author=>"William Shakespeare"},
    {:title=>"Pride and Prejudice",
      :author=>"Jane Austen"}]}

What is the nest way to accomplish this?

解决方案

For rails 3.0.0+ or higher version there is the deep_merge function for ActiveSupport that does exactly what you ask for.

这篇关于Ruby:合并嵌套散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆