bfcoder bfcoder - 1 year ago 63
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 .

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download