Created
February 7, 2011 21:03
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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