如何合并这两个哈希值:
{:car => {:color => "red"}}
{:car => {:speed => "100mph"}}
获得:
{:car => {:color => "red", :speed => "100mph"}}
答案 0 :(得分:61)
有Hash#merge
方法:
ruby-1.9.2 > a = {:car => {:color => "red"}}
=> {:car=>{:color=>"red"}}
ruby-1.9.2 > b = {:car => {:speed => "100mph"}}
=> {:car=>{:speed=>"100mph"}}
ruby-1.9.2 > a.merge(b) {|key, a_val, b_val| a_val.merge b_val }
=> {:car=>{:color=>"red", :speed=>"100mph"}}
如果需要合并嵌套的哈希值,可以创建递归方法:
def merge_recursively(a, b)
a.merge(b) {|key, a_item, b_item| merge_recursively(a_item, b_item) }
end
ruby-1.9.2 > merge_recursively(a,b)
=> {:car=>{:color=>"red", :speed=>"100mph"}}
答案 1 :(得分:36)
Rails 3.0 +
a = {:car => {:color => "red"}}
b = {:car => {:speed => "100mph"}}
a.deep_merge(b)
=> {:car=>{:color=>"red", :speed=>"100mph"}}
来源:https://speakerdeck.com/u/jeg2/p/10-things-you-didnt-know-rails-could-do 幻灯片24
此外,
答案 2 :(得分:8)
您可以使用ruby库中定义的merge
方法。 https://ruby-doc.org/core-2.2.0/Hash.html#method-i-merge
h1={"a"=>1,"b"=>2}
h2={"b"=>3,"c"=>3}
h1.merge!(h2)
它会为您输出{"a"=>1,"b"=>3,"c"=>3}
Merge
方法不允许重复密钥,因此密钥b将从 2到3 覆盖。
要克服上述问题,您可以像这样破解merge
方法。
h1.merge(h2){|k,v1,v2|[v1,v2]}
上面的代码片段将为您提供输出
{"a"=>1,"b"=>[2,3],"c"=>3}
答案 3 :(得分:2)
h1 = {:car => {:color => "red"}}
h2 = {:car => {:speed => "100mph"}}
h3 = h1[:car].merge(h2[:car])
h4 = {:car => h3}