Sha256: bc3001d76d5dd4f5d11fc7d468d2b6973081b1d3cc084a805e535271043c9611

Contents?: true

Size: 1.26 KB

Versions: 12

Compression:

Stored size: 1.26 KB

Contents

#--
# Credits for original version goes to Zallus Kanite and Gavin Sinclair.
#++

#--
# Hash#graph! is only useful for Hash. It is not generally
# applicable to Enumerable.
#++

require 'facet/hash/graph'

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.
  #
  #   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

  # no longer used
  #alias_method( :build_hash, :graph )
  #alias_method( :build_hash!, :graph! )
end



#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class TCEnumerable < Test::Unit::TestCase

    def test_graph
      numbers  = (1..3)
      squares  = numbers.graph{ |n| [n, n*n] }
      assert_equal( {1=>1, 2=>4, 3=>9}, squares )
      sq_roots = numbers.graph{ |n| [n*n, n] }
      assert_equal( {1=>1, 4=>2, 9=>3}, sq_roots )
    end

  end

=end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
facets-1.4.0 lib/facets/core/enumerable/graph.rb
facets-1.4.1 lib/facets/core/enumerable/graph.rb
facets-1.4.2 lib/facets/core/enumerable/graph.rb
facets-1.4.3 lib/facets/core/enumerable/graph.rb
facets-1.4.4 lib/facets/core/enumerable/graph.rb
facets-1.4.5 lib/facets/core/enumerable/graph.rb
facets-1.7.0 lib/facets/core/enumerable/graph.rb
facets-1.7.30 lib/facets/core/enumerable/graph.rb
facets-1.7.38 lib/facets/core/enumerable/graph.rb
facets-1.7.46 lib/facets/core/enumerable/graph.rb
facets-1.8.0 lib/facets/core/enumerable/graph.rb
facets-1.8.8 lib/facets/core/enumerable/graph.rb