Skip to content

Instantly share code, notes, and snippets.

@steshaw
Forked from lengarvey/refine_hash.rb
Created May 18, 2015 02:38
Show Gist options
  • Save steshaw/de42ca258fa205abaf7b to your computer and use it in GitHub Desktop.
Save steshaw/de42ca258fa205abaf7b to your computer and use it in GitHub Desktop.
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