Sha256: c26a431f73d97a1e105c473166038855914f832f76fc8b2b758e88a7553b968c

Contents?: true

Size: 805 Bytes

Versions: 7

Compression:

Stored size: 805 Bytes

Contents

module Enumerable

  # Like `#map`/`#collect`, but 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 }
  #
  # CREDIT: Andrew Dudzik (adudzik), Trans

  def graph(&yld)
    if yld
      h = {}
      each do |*kv|
        r = yld[*kv]
        case r
        when Hash
          nk, nv = *r.to_a[0]
        when Range
          nk, nv = r.first, r.last
        else
          nk, nv = *r
        end
        h[nk] = nv
      end
      h
    else
      Enumerator.new(self,:graph)
    end
  end

  # Alias for #graph, which stands for "map hash".
  alias_method :mash, :graph

end

Version data entries

7 entries across 6 versions & 1 rubygems

Version Path
facets-2.9.3 lib/core/facets/enumerable/graph.rb
facets-2.9.2 lib/core/facets/enumerable/graph.rb
facets-2.9.2 src/core/facets/enumerable/graph.rb
facets-2.9.1 lib/core/facets/enumerable/graph.rb
facets-2.9.0 lib/core/facets/enumerable/graph.rb
facets-2.9.0.pre.2 lib/core/facets/enumerable/graph.rb
facets-2.9.0.pre.1 lib/core/facets/enumerable/graph.rb