-
-
Save steshaw/de42ca258fa205abaf7b 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
class Hash | |
def safe_invert | |
lazy | |
.map {|a, b| [b, a]} | |
.group_by {|a| a[0]} | |
.map {|a, b| [a, b.collect {|c| c[1]}]} | |
.to_h | |
end | |
end | |
h = {a: 1, b: 1, c: 2} | |
p h.invert #=> {1=>:b, 2=>:c} | |
p h.safe_invert #=> {1=>[:a, :b], 2=>[:c]} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment