Module: Corefines::Enumerable::IndexBy

Defined in:
lib/corefines/enumerable.rb

Instance Method Summary collapse

Instance Method Details

#index_by {|obj| ... } ⇒ Hash

Convert enumerable into a Hash, iterating over each element where the provided block must return the key to be used to map to the value.

It's similar to Enumerable#group_by, but when two elements corresponds to the same key, then only the last one is preserved in the resulting Hash.

Examples:

people.index_by(&:login)
=> { "flynn" => <Person @login="flynn">, "bradley" => <Person @login="bradley">, ...}
people.index_by.each(&:login)
=> { "flynn" => <Person @login="flynn">, "bradley" => <Person @login="bradley">, ...}

Yields:

  • (obj)

    gives each element to the block.

Yield Returns:

  • the key to be used to map to the value.


28
29
30
31
32
33
34
35
36
37
# File 'lib/corefines/enumerable.rb', line 28

module IndexBy
  Support.classes_including_module(::Enumerable) do |klass|

    refine klass do
      def index_by
        ::Hash[map { |elem| [ yield(elem), elem ] }]
      end
    end
  end
end