How to merge array of hashes to get hash of arrays of values How to merge array of hashes to get hash of arrays of values arrays arrays

How to merge array of hashes to get hash of arrays of values


Take your pick:

hs.reduce({}) {|h,pairs| pairs.each {|k,v| (h[k] ||= []) << v}; h}hs.map(&:to_a).flatten(1).reduce({}) {|h,(k,v)| (h[k] ||= []) << v; h}

I'm strongly against messing with the defaults for hashes, as the other suggestions do, because then checking for a value modifies the hash, which seems very wrong to me.


h = Hash.new{|h,k| h[k]=[]}hs.map(&:to_a).flatten(1).each{|v| h[v[0]] << v[1]}


How's this?

def collect_values(hashes)  h = Hash.new{|h,k| h[k]=[]}  hashes.each_with_object(h) do |h, result|    h.each{ |k, v| result[k] << v }  endend

Edit - Also possible with inject, but IMHO not as nice:

def collect_values( hashes )  h = Hash.new{|h,k| h[k]=[]}  hashes.inject(h) do |result, h|    h.each{ |k, v| result[k] << v }    result  endend