Skip to content

Instantly share code, notes, and snippets.

@spetschu
Created February 7, 2011 21:03
Show Gist options
  • Save spetschu/815209 to your computer and use it in GitHub Desktop.
Save spetschu/815209 to your computer and use it in GitHub Desktop.
Ruby Hash subtract method extended to work for Array and Hash values within the Hash.
# Examples
# {:foo => [1,2,3,4]} - {:foo => [1,2]}
# results in {:foo => [3,4]}
#
# {:bar => {:baz => [8,9]}, :buz => "deleteme"} - {:bar => 8, :buz => "deleteme"}
# results in {:bar => {:baz => [9]}, :buz => nil}
#
class Hash
def - (h)
self.merge(h) do |k, old, new|
case old
when Array then (new.class == Array) ? (old - new) : (old - [new])
when Hash then (new.class == Hash) ? (old - new) : old
else (old == new) ? nil : old
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment