Combining two hashes by concatenating arrays

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

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

I expect the convolute method to give:

 h1.convolute(h2) #=> {:a => [1], b: [2, 3, 4], c: [5]} 
+4
source share
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

+12
source

If you do not need to change h2 , then:

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

If you want to leave only h2 :

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

And if you need this specific order:

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

Source: https://habr.com/ru/post/1402169/


All Articles