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 = 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]}
In order to combine (concatenate) two arrays, we find its length stored in aLen and bLen respectively. Then, we create a new integer array result with length aLen + bLen . Now, in order to combine both, we copy each element in both arrays to result by using arraycopy() function.
We can merge two hashes using the merge() method. When using the merge() method: Each new entry is added to the end. Each duplicate-key entry's value overwrites the previous value.
The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.
This is exactly what Hash#merge
does if you give it a block:
h1.merge(h2) do |key, v1, v2|
v1 + v2
end
http://rubydoc.info/stdlib/core/1.9.2/Hash:merge
If you don't care about modifying h2
then:
h1.each_with_object(h2) { |(k, v), h| h[k] += v }
If you want to leave h2
alone:
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With