find the symmetric difference of two maps in ruby

To find the symmetric difference of two maps (also known as hash in Ruby), you can use the following code:

main.rb
map1 = { a: 1, b: 2, c: 3 }
map2 = { b: 4, c: 3, d: 6 }

symmetric_difference = map1.merge(map2) do |key, old_value, new_value|
  if old_value == new_value
    nil
  else
    [old_value, new_value]
  end
end.compact.to_h

puts symmetric_difference # Output: { :a => 1, :b => [2, 4], :d => 6 }
293 chars
13 lines

Explanation:

  • map1 and map2 are the two maps whose symmetric difference we want to find
  • We merge map1 and map2, and for each common key, we decide whether to keep the old value or the new value
  • If the old value is equal to the new value, we discard the key-value pair (return nil)
  • Otherwise, we keep both values in an array ([old_value, new_value])
  • We then remove any nil values and convert the result back to a hash
  • The final hash represents the symmetric difference between the two maps

gistlibby LogSnag