Sha256: 77b330dac2dfd55ad6b4b1a7826ba47c6f0e6c0920f2b2bee2fa31093a1ae0b4

Contents?: true

Size: 1.24 KB

Versions: 10

Compression:

Stored size: 1.24 KB

Contents

# TITLE:
#
#   Hash Inverse
#
# SUMMARY:
#
#   Create a "true" inverse hash by storing mutliple values
#   in Arrays.
#
# CREDITS:
#
#   - Tilo Sloboda

#
class Hash

  # CREDIT Tilo Sloboda

  # 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 TestHashInverse < Test::Unit::TestCase

    def test_inverse
      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

10 entries across 10 versions & 1 rubygems

Version Path
facets-2.0.1 lib/core/facets/hash/inverse.rb
facets-2.0.0 lib/core/facets/hash/inverse.rb
facets-2.0.2 lib/core/facets/hash/inverse.rb
facets-2.1.0 lib/core/facets/hash/inverse.rb
facets-2.1.1 lib/core/facets/hash/inverse.rb
facets-2.1.2 lib/core/facets/hash/inverse.rb
facets-2.0.3 lib/core/facets/hash/inverse.rb
facets-2.0.4 lib/core/facets/hash/inverse.rb
facets-2.0.5 lib/core/facets/hash/inverse.rb
facets-2.1.3 lib/core/facets/hash/inverse.rb