Subtract two hashes in Ruby

hash, ruby

Solution

Use the `reject` method:

class Hash
  def difference(other)
    reject do |k,v|
      other.has_key? k
    end
  end
end

To only reject key/value pairs if the values are identical (as per mallanaga's suggestion via a comment on my original answer, which I have deleted):

class Hash
  def difference(other)
    reject do |k,v|
      other.has_key?(k) && other[k] == v
    end
  end
end

Problem

Can the `hash` class be modified so that given two hashes, a new hash containing only keys that are present in one hash but not the other can be created? E.g.: ``` h1 = {"Cat" => 100, "Dog" => 5, "Bird" => 2, "Snake" => 10} h2 = {"Cat" => 100, "Dog" => 5, "Bison" => 30} h1.difference(h2) = {"Bird" => 2, "Snake" => 10} ``` Optionally, the `difference` method could include any key/value pairs such that the key is present in both hashes but the value differs between them.

Original source

Related problems