Created
May 17, 2015 23:37
-
-
Save lengarvey/e056deeba0572675e209 to your computer and use it in GitHub Desktop.
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
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