Skip to content

Instantly share code, notes, and snippets.

@lengarvey
Created May 17, 2015 23:37
Show Gist options
  • Save lengarvey/e056deeba0572675e209 to your computer and use it in GitHub Desktop.
Save lengarvey/e056deeba0572675e209 to your computer and use it in GitHub Desktop.
module HashExtensions
refine Hash do
# Safely invert
def invert
self.reduce({}) do |hash,(key,value)|
hash.merge!(
value => (hash[value] || []) + [key]
)
end
end
end
end
class MyApp
using HashExtensions
def self.foo(h)
h.invert
end
end
h = {a: 1, b: 1, c: 2}
p h.invert #=> {1=>:b, 2=>:c}
p MyApp.foo(h) #=> 1=>[:a, :b], 2=>[:c]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment