Module: DataMapper::Support::Enumerable

Included in:
Array
Defined in:
lib/data_mapper/support/enumerable.rb

Instance Method Summary collapse

Instance Method Details

#group_byObject

Group a collection of elements into groups within a Hash. The value returned by the block passed to group_by is the key, and the value is an Array of items matching that key.

Example

names = %w{ sam scott amy robert betsy }
names.group_by { |name| name.size }
=> { 3 => [ "sam", "amy" ], 5 => [ "scott", "betsy" ], 6 => [ "robert" ]}


14
15
16
17
18
# File 'lib/data_mapper/support/enumerable.rb', line 14

def group_by
  inject(Hash.new { |h,k| h[k] = [] }) do |memo,item|
    memo[yield(item)] << item; memo
  end
end