如何在 ruby 中将一个散列与另一个散列相结合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13654562/
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 combine one hash with another hash in ruby
提问by thefonso
I have two hashes...
我有两个哈希...
a = {:a => 5}
b = {:b => 10}
I want...
我想要...
c = {:a => 5,:b => 10}
How do I create hash c?
我如何创建哈希 c?
回答by tadman
It's a pretty straight-forward operation if you're just interleaving:
如果你只是交错,这是一个非常直接的操作:
c = a.merge(b)
If you want to actually add the values together, this would be a bit trickier, but not impossible:
如果您想将这些值实际相加,这会有点棘手,但并非不可能:
c = a.dup
b.each do |k, v|
c[k] ||= 0
c[k] += v
end
The reason for a.dupis to avoid mangling the values in the ahash, but if you don't care you could skip that part. The ||=is used to ensure it starts with a default of 0as nil + 1is not valid.
原因a.dup是为了避免修改a散列中的值,但如果您不在乎,可以跳过该部分。将||=用于确保它的默认启动0为nil + 1无效。
回答by Prabhakar Undurthi
As everyone is saying you can use merge method to solve your problem. However there is slightly some problem with using the merge method. Here is why.
正如大家所说,您可以使用合并方法来解决您的问题。但是,使用合并方法存在一些问题。这是为什么。
person1 = {"name" => "MarkZuckerberg", "company_name" => "Facebook", "job" => "CEO"}
person2 = {"name" => "BillGates", "company_name" => "Microsoft", "position" => "Chairman"}
Take a look at these two fields name and company_name. Here name and company_name both are same in the two hashes(I mean the keys). Next job and position have different keys.
看看这两个字段名称和公司名称。这里 name 和 company_name 在两个哈希中都是相同的(我的意思是键)。下一个工作和职位有不同的键。
When you try to merge two hashes person1 and person2 If person1 and person2 keys are same? then the person2 key value will override the peron1 key value . Here the second hash will override the first hash fields because both are same. Here name and company name are same. See the result.
当您尝试合并两个散列 person1 和 person2 时,如果 person1 和 person2 键相同?那么 person2 键值将覆盖 peron1 键值。这里第二个散列将覆盖第一个散列字段,因为它们是相同的。这里名称和公司名称相同。看看结果。
people = person1.merge(person2)
Output: {"name"=>"BillGates", "company_name"=>"Microsoft",
"job"=>"CEO", "position"=>"Chairman"}
However if you don't want your second hash to override the first hash. You can do something like this
但是,如果您不希望第二个哈希值覆盖第一个哈希值。你可以做这样的事情
people = person1.merge(person2) {|key, old, new| old}
Output: {"name"=>"MarkZuckerberg", "company_name"=>"Facebook",
"job"=>"CEO", "position"=>"Chairman"}
It is just a quick note when using merge()
这只是使用 merge() 时的快速说明
回答by Andbdrew
I think you want
我想你想要
c = a.merge(b)
you can check out the docs at http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-merge
您可以在http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-merge查看文档
回答by jboursiquot
Use merge method:
使用合并方法:
c = a.merge b

