Sha256: 373cbe0c78fe8a3f0e6b83b479216bc746b3355f5c075d758d935d22b5df9f0f

Contents?: true

Size: 718 Bytes

Versions: 10

Compression:

Stored size: 718 Bytes

Contents

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
  #
  # CREDIT: Tilo Sloboda

  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

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
facets-2.8.4 lib/core/facets/hash/inverse.rb
facets-2.8.3 lib/core/facets/hash/inverse.rb
facets-2.8.2 lib/core/facets/hash/inverse.rb
facets-2.8.1 lib/core/facets/hash/inverse.rb
facets-2.8.0 lib/core/facets/hash/inverse.rb
facets-2.7.0 lib/core/facets/hash/inverse.rb
facets-2.6.0 lib/core/facets/hash/inverse.rb
facets-2.5.1 lib/core/facets/hash/inverse.rb
facets-2.5.0 lib/core/facets/hash/inverse.rb
facets-2.5.2 lib/core/facets/hash/inverse.rb