Sha256: 0d871adb04e90c62a5e581623b034e9b7f907381a207a184bb4f625f66f00c7f

Contents?: true

Size: 771 Bytes

Versions: 3

Compression:

Stored size: 771 Bytes

Contents

#--
# Credit goes to Tilo Sloboda.
#++
class Hash
  # Create a "true" inverse hash by storing mutliple values
  # in Arrays.
  #
  #   require 'facet/hash/inverse'
  #
  #   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

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
facets-0.7.0 lib/facet/hash/inverse.rb
facets-0.7.1 lib/facet/hash/inverse.rb
facets-0.7.2 lib/facet/hash/inverse.rb