uniq方法 - 如何合并Ruby哈希




ruby迭代器 (3)

如何合并这两个哈希:

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

要得到:

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


您可以使用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}

h1 = {:car => {:color => "red"}}
h2 = {:car => {:speed => "100mph"}}
h3 = h1[:car].merge(h2[:car])
h4 = {:car => h3}






hashmap