Module: Enumerable

Defined in:
lib/map_h.rb

Instance Method Summary collapse

Instance Method Details

#map_hObject

Similar to Enumerable#map, but builds a hash of the results using the original value as the key.

['john', 'paul', 'george', 'ringo'].map_h { |name| name.length }
# => {'john' => 4, 'paul' => 4, 'george' => 6, 'ringo' => 5}


7
8
9
10
11
12
13
# File 'lib/map_h.rb', line 7

def map_h
  {}.tap do |result|
    each do |key|
      result[key] = yield key
    end
  end
end