anyavacy anyavacy - 2 months ago 12
Ruby Question

merging and appending hashes in ruby

I have two hashes like this

h1 = {:a=>[:client]}
h2 = {:a=>[:user]}


and I would love to merge them together but keep the values from both hashes like:

{:a=>[:user, :client]}


I tried the merge method but it remove one value and keep only one. I am using
ruby 2.2

Answer

Try inject:

h1.inject(h2) do |memo, (k,v)| 
  memo[k] ||= []
  memo[k] += v
  memo
end

memo starts off as the value passed to inject, h2. It is replaced on each iteration by the return value of the block. In our case we update memo and return it, thus building up memo until on the final iteration it is returned as the answer.

The first line in the block memo[k] ||= [] isn't strictly needed if there are no nil values or missing keys.

Comments