bfcoder bfcoder - 10 months ago 46
Ruby Question

merging ruby hash with array of values into another hash with array of values

I can't seem to find anywhere that talks about doing this.

Say I have a hash

and I want to merge in this hash
to result with this hash

Or how about
merged with
to get


Answer Source
{"23"=>[0,3]}.merge({"23"=>[2,3]}){ |key,oldval,newval| oldval | newval }
#=> {"23"=>[0, 3, 2]}

More generic way to handle non-array values:

{"23"=>[0,3]}.merge({"23"=>[2,3]}) do |key, oldval, newval|
  (newval.is_a?(Array) ? (oldval + newval) : (oldval << newval)).uniq

Updated with a Marc-André Lafortune's hint .