-
-
Save simeonwillbanks/5630343 to your computer and use it in GitHub Desktop.
#ruby #hash #invert
This file contains hidden or 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
require './hash_inverse' | |
describe Hash do | |
describe "when empty and asked for the inverse" do | |
it "returns an empty hash" do | |
{}.inverse.must_equal Hash.new | |
end | |
end | |
describe "when mapping are unique and asked for the inverse" do | |
it "returns the inverse hash" do | |
{a: 1, b: 2, c: 3}.inverse.must_equal({1=>[:a], 2=>[:b], 3=>[:c]}) | |
end | |
end | |
describe "when mapping are not unique and asked for the inverse" do | |
it "returns the one to many key to values" do | |
{a: 1, b: 1, c: 2}.inverse.must_equal({1=>[:a, :b], 2=>[:c]}) | |
end | |
end | |
end |
This file contains hidden or 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 | |
# like invert but not lossy | |
#{1=>2,3=>2,2=>4}.inverse => {2=>[1, 3], 4=>[2]} | |
def inverse | |
self.each_with_object({}){ |pair,o| k,v = *pair; o[v] ||=[]; o[v] << k} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment