← All languages
Ruby method of the day
Random

group_by

Group elements into a hash by the block's return value.

Description

The group_by method groups the elements of the collection into a hash, where the keys are the values returned by the block and the values are arrays of elements that produced that key.

This is extremely useful for categorizing or partitioning data by some property. The order of elements within each group is preserved from the original collection.

Without a block, it returns an Enumerator. This method is part of the Enumerable module and works on arrays, hashes, ranges, and other enumerable objects.

Arguments

NameDescriptionOptional
{ |item| ... } A block whose return value determines the grouping key. No

Example

[1, 2, 3, 4, 5].group_by { |n| n.even? }
# {false=>[1, 3, 5], true=>[2, 4]}

%w[cat car bat bar].group_by { |s| s[0] }
# {"c"=>["cat", "car"], "b"=>["bat", "bar"]}

Reference