Sha256: c0308780850e92493e80c7bba8564a64dd2ac1cb1f305917ca40390225c15a03
Contents?: true
Size: 1.04 KB
Versions: 5
Compression:
Stored size: 1.04 KB
Contents
#-- # Credit goes to Tilo Sloboda. #++ class Hash # Create a "true" inverse hash by storing mutliple values # in Arrays. # # h = {"a"=>3, "b"=>3, "c"=>3, "d"=>2, "e"=>9, "f"=>3, "g"=>9} # # h.invert #=> {2=>"d", 3=>"f", 9=>"g"} # h.inverse #=> {2=>"d", 3=>["f", "c", "b", "a"], 9=>["g", "e"]} # h.inverse.inverse #=> {"a"=>3, "b"=>3, "c"=>3, "d"=>2, "e"=>9, "f"=>3, "g"=>9} # h.inverse.inverse == h #=> true # def inverse i = Hash.new self.each_pair{ |k,v| if (Array === v) v.each{ |x| i[x] = ( i.has_key?(x) ? [k,i[x]].flatten : k ) } else i[v] = ( i.has_key?(v) ? [k,i[v]].flatten : k ) end } return i end end # _____ _ # |_ _|__ ___| |_ # | |/ _ \/ __| __| # | | __/\__ \ |_ # |_|\___||___/\__| # =begin test require 'test/unit' class TCHash < Test::Unit::TestCase def test_each_with_key h1 = { :a=>1, :b=>2, :c=>2 } h2 = h1.inverse assert_equal( {1=>:a, 2=>[:b,:c]}, h2 ) end end =end
Version data entries
5 entries across 5 versions & 1 rubygems