Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging two hashes by concatenating the arrays

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]}
like image 649
sawa Avatar asked Mar 19 '12 04:03

sawa


People also ask

How to concatenate an array?

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.

How do you add two hashes together?

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.

How to concatenate array in js?

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.


2 Answers

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

like image 153
Theo Avatar answered Oct 05 '22 09:10

Theo


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 }
like image 22
mu is too short Avatar answered Oct 05 '22 11:10

mu is too short