Sha256: 1ca2a66e331a087abe2412877bc1b2dd8edeafa0eebc0bb0e3eef6556906f6b4

Contents?: true

Size: 1.04 KB

Versions: 1

Compression:

Stored size: 1.04 KB

Contents

#--
# Credits for original work goes to Zallus Kanite and Gavin Sinclair.
#++
module Enumerable
  #
  # Like <tt>#map</tt>/<tt>#collect</tt>, but it generates a Hash.  The block
  # is expected to return two values: the key and the value for the new hash.
  #
  #   require 'facet/enumberable/graph'
  #
  #   numbers  = (1..3)
  #   squares  = numbers.graph { |n| [n, n*n] }   # { 1=>1, 2=>4, 3=>9 }
  #   sq_roots = numbers.graph { |n| [n*n, n] }   # { 1=>1, 4=>2, 9=>3 }
  #
  def graph(&yld)
    if yld
      inject({}) do |h,kv|
        nk, nv = yld[*kv]
        h[nk] = nv
        h
      end
    else
      Hash[*self.to_a.flatten]
    end
  end
  alias_method( :build_hash, :graph )
    
#old version
#    result = {}
#    if block_given?
#      self.each do |elt|
#        key, value = yield(elt)
#        result[key] = value
#      end
#    else
#      Hash[*self.to_a.flatten]
#    end
#    result
#  end


  # As with map_hash but acts in place.
  def graph!( &blk )
    self.replace( map_hash( &blk ) )
  end
  alias_method( :build_hash!, :graph! )

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
facets-0.6.3 lib/facet/enumerable/graph.rb