Sha256: 48b25991279248902f50eae290a2b9c6da6da00a0c48770b1bed8bb9f0e2647a
Contents?: true
Size: 1.1 KB
Versions: 21
Compression:
Stored size: 1.1 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( :a, h2[1] ) assert( h2[2].include?(:b) ) assert( h2[2].include?(:c) ) end end =end
Version data entries
21 entries across 21 versions & 1 rubygems