Method: Enumerable#index_by

Defined in:
lib/active_support/core_ext/enumerable.rb

#index_byObject

Convert an enumerable to a hash, using the block result as the key and the element as the value.

people.index_by(&:login)
# => { "nextangle" => <Person ...>, "chade-" => <Person ...>, ...}

people.index_by { |person| "#{person.first_name} #{person.last_name}" }
# => { "Chade- Fowlersburg-e" => <Person ...>, "David Heinemeier Hansson" => <Person ...>, ...}


52
53
54
55
56
57
58
59
60
# File 'lib/active_support/core_ext/enumerable.rb', line 52

def index_by
  if block_given?
    result = {}
    each { |elem| result[yield(elem)] = elem }
    result
  else
    to_enum(:index_by) { size if respond_to?(:size) }
  end
end