通过连接数组合并两个哈希值

时间:2022-06-23 12:21:13

Given two hashes whose values are arrays, what is the best way to merge them so that when the two shares some key, the resulting value will be the concatenation of the values of the original two hashes? For example, given two hashes h1 and h2:

给定两个值为数组的哈希值,合并它们的最佳方法是什么,这样当两个共享一些键时,结果值将是原始两个哈希值的串联?例如,给定两个哈希值h1和h2:

h1 = Hash.new{[]}.merge(a: [1], b: [2, 3])
h2 = Hash.new{[]}.merge(b: [4], c: [5])

I expect that the method convolute will give:

我希望旋转方法会给出:

h1.convolute(h2) #=> {:a => [1], b: [2, 3, 4], c: [5]}

2 个解决方案

#1


12  

This is exactly what Hash#merge does if you give it a block:

如果你给它一个块,这正是Hash#merge所做的:

h1.merge(h2) do |key, v1, v2|
  v1 + v2
end

http://rubydoc.info/stdlib/core/1.9.2/Hash:merge

http://rubydoc.info/stdlib/core/1.9.2/Hash:merge

#2


2  

If you don't care about modifying h2 then:

如果你不关心修改h2那么:

h1.each_with_object(h2) { |(k, v), h| h[k] += v }

If you want to leave h2 alone:

如果你想单独留下h2:

h1.each_with_object(h2.dup) { |(k, v), h| h[k] += v }

And if you want that specific order:

如果您想要特定订单:

h2.each_with_object(h1.dup) { |(k, v), h| h[k] += v }

#1


12  

This is exactly what Hash#merge does if you give it a block:

如果你给它一个块,这正是Hash#merge所做的:

h1.merge(h2) do |key, v1, v2|
  v1 + v2
end

http://rubydoc.info/stdlib/core/1.9.2/Hash:merge

http://rubydoc.info/stdlib/core/1.9.2/Hash:merge

#2


2  

If you don't care about modifying h2 then:

如果你不关心修改h2那么:

h1.each_with_object(h2) { |(k, v), h| h[k] += v }

If you want to leave h2 alone:

如果你想单独留下h2:

h1.each_with_object(h2.dup) { |(k, v), h| h[k] += v }

And if you want that specific order:

如果您想要特定订单:

h2.each_with_object(h1.dup) { |(k, v), h| h[k] += v }