19

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!

7
  • Well, what have you tried? Anyway, looked at inject? There might be a more clever zip-by-key approach, though... Commented Jun 23, 2012 at 18:15
  • @pst: Or, better, reduce? :) Commented Jun 23, 2012 at 18:16
  • @SergioTulentsev Or something :-) Commented Jun 23, 2012 at 18:16
  • I've looked at both inject and reduce but I honestly don't understand how those function work and what they are capable of doing. They have always been a mystery to me. :\ Commented Jun 23, 2012 at 18:31
  • 1
    What do you mean you looked at both, they are aliased methods. I guess @SergioTulentsev was trying to make a joke. If you want to understand how they work, you should read up on folds: en.wikipedia.org/wiki/Fold_(higher-order_function) Commented Jun 23, 2012 at 19:00

1 Answer 1

38
{ "23" => [0,3] }.merge({ "23" => [2,3] }) do |key, oldval, newval| 
  oldval | newval
end
#=> {"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 .

Sign up to request clarification or add additional context in comments.

5 Comments

Didn't know merge could take a block. Sweet!
That is awesome. Works perfectly! +1 for megas! Thanks!
Better, shorter, faster to use oldval | newval then (oldval + newval).uniq
Awesome, thanks Marc-André Lafortune Faster and shorter is always better. :]
How to merge everything? I mean if there is 23 => [], 24 => [], I want to merge all to one single array []

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.