Sha256: b9b42047abe766729f2fa6eda9f7aef7f40940a3d9f0326f003144add96bd4e3

Contents?: true

Size: 695 Bytes

Versions: 3

Compression:

Stored size: 695 Bytes

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 )
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
facets-0.7.0 lib/facet/enumerable/graph.rb
facets-0.7.1 lib/facet/enumerable/graph.rb
facets-0.7.2 lib/facet/enumerable/graph.rb