Module: DataMapper::Support::EnumerableExtensions
- Included in:
- Array
- Defined in:
- lib/data_mapper/support/enumerable.rb
Overview
Extends Array to include an instance method for grouping objects
Instance Method Summary collapse
-
#group_by ⇒ Object
Group a collection of elements into groups within a Hash.
Instance Method Details
#group_by ⇒ Object
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" ]}
22 23 24 25 26 |
# File 'lib/data_mapper/support/enumerable.rb', line 22 def group_by inject(Hash.new { |h,k| h[k] = [] }) do |memo,item| memo[yield(item)] << item; memo end end |