Skip to content

Instantly share code, notes, and snippets.

@aaronbbrown
Created August 29, 2012 15:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaronbbrown/3514818 to your computer and use it in GitHub Desktop.
Save aaronbbrown/3514818 to your computer and use it in GitHub Desktop.
Subtract Hashes
#!/usr/bin/env ruby
require 'pp'
class Hash
def subtract (h)
result = {}
self.each do |k,v|
result[k] = (self[k] - h[k]) if h[k]
end
result
end
end
h1 = { 'a' => 5,
'b' => 10,
'c' => 15 }
h2 = { 'a' => 20,
'b' => 30,
'c' => 40 }
pp h2.subtract(h1)
# -> {"a"=>15, "b"=>20, "c"=>25}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment