Sha256: 834447b4e66cc1d2631dc1becb0691fdc4cb38f7f43a245f364fbe6fe8a51ec4

Contents?: true

Size: 876 Bytes

Versions: 3

Compression:

Stored size: 876 Bytes

Contents

module Enumerable

  # Like <tt>#map</tt>/<tt>#collect</tt>, 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.mash { |n| [n, n*n] }   # { 1=>1, 2=>4, 3=>9 }
  #   sq_roots = numbers.mash { |n| [n*n, n] }   # { 1=>1, 4=>2, 9=>3 }
  #
  # The name "mash" stands for "map hash".
  #
  # CREDIT: Andrew Dudzik (adudzik), Trans

  def mash(&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,:mash)
    end
  end

  # Alias for #mash. This is the original name of this method.
  alias_method :graph, :mash

end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
facets-2.8.2 lib/core/facets/enumerable/mash.rb
facets-2.8.1 lib/core/facets/enumerable/mash.rb
facets-2.8.0 lib/core/facets/enumerable/mash.rb