如何合并Ruby哈希

时间:2011-12-07 12:21:05

标签: ruby hashmap

如何合并这两个哈希值:

{:car => {:color => "red"}}
{:car => {:speed => "100mph"}}

获得:

{:car => {:color => "red", :speed => "100mph"}}

4 个答案:

答案 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)

Hash#deep_merge

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

此外,

http://apidock.com/rails/v3.2.13/Hash/deep_merge

答案 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}