Method: Enumerable#mash

Defined in:
lib/core/facets/enumerable/mash.rb

#mash(&yld) ⇒ Object

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

CREDIT: Andrew Dudzik (adudzik), Trans


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/core/facets/enumerable/mash.rb', line 12

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,:graph)
  end
end