h1 = {"Cat" => 100, "Dog" => 5, "Bird" => 2, "Snake" => 10} h2 = {"Cat" => 999, "Dog" => 5, "Bison" => 30}
Case 1: save all key / value pairs k=>v in h1 for which there is no k key in h2
This is one way:
h1.dup.delete_if { |k,_| h2.key?(k) } #=> {"Bird"=>2, "Snake"=>10}
This is different:
class Array alias :spaceship :<=> def <=>(o) first <=> o.first end end (h1.to_a - h2.to_a).to_h #=> {"Bird"=>2, "Snake"=>10} class Array alias :<=> :spaceship remove_method(:spaceship) end
Case 2: store all key / value pairs in h1 that are not in h2
All you need for this:
(h1.to_a - h2.to_a).to_h #=> {"Cat"=>100, "Bird"=>2, "Snake"=>10}
The # to_h array was introduced in Ruby 2.0. For earlier versions, use Hash [] .
source share