bfcoder bfcoder - 2 months ago 9
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

{"23"=>[0,3]}
and I want to merge in this hash
{"23"=>[2,3]}
to result with this hash
{"23"=>[0,2,3]}


Or how about
{"23"=>[3]}
merged with
{"23"=>0}
to get
{"23"=>[0,3]}


Thanks!

Answer
{"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
end

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

Comments