如何合并 Ruby 哈希
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8415240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to merge Ruby hashes
提问by skyporter
How can I merge these two hashes:
如何合并这两个哈希值:
{:car => {:color => "red"}}
{:car => {:speed => "100mph"}}
To get:
要得到:
{:car => {:color => "red", :speed => "100mph"}}
回答by Aliaksei Kliuchnikau
There is a Hash#mergemethod:
有一个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"}}
You can create a recursive method if you need to merge nested hashes:
如果需要合并嵌套哈希,可以创建递归方法:
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"}}
回答by Andrei
Rails 3.0+
轨道 3.0+
a = {:car => {:color => "red"}}
b = {:car => {:speed => "100mph"}}
a.deep_merge(b)
=> {:car=>{:color=>"red", :speed=>"100mph"}}
Source: https://speakerdeck.com/u/jeg2/p/10-things-you-didnt-know-rails-could-doSlide 24
来源:https: //speakerdeck.com/u/jeg2/p/10-things-you-didnt-know-rails-could-doSlide 24
Also,
还,
回答by Mukesh Kumar Gupta
You can use the mergemethod defined in the ruby library. https://ruby-doc.org/core-2.2.0/Hash.html#method-i-merge
您可以使用mergeruby 库中定义的方法。https://ruby-doc.org/core-2.2.0/Hash.html#method-i-merge
Example
例子
h1={"a"=>1,"b"=>2}
h2={"b"=>3,"c"=>3}
h1.merge!(h2)
It will give you output like this {"a"=>1,"b"=>3,"c"=>3}
它会给你这样的输出 {"a"=>1,"b"=>3,"c"=>3}
Mergemethod does not allow duplicate key, so key b will be overwritten from 2 to 3.
Merge方法不允许重复键,因此键 b 将从2覆盖到 3。
To overcome the above problem, you can hack mergemethod like this.
为了克服上述问题,您可以merge像这样破解方法。
h1.merge(h2){|k,v1,v2|[v1,v2]}
The above code snippet will be give you output
上面的代码片段会给你输出
{"a"=>1,"b"=>[2,3],"c"=>3}
回答by bor1s
h1 = {:car => {:color => "red"}}
h2 = {:car => {:speed => "100mph"}}
h3 = h1[:car].merge(h2[:car])
h4 = {:car => h3}

