End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
Enumerable#group_by
group_by {|element| ... } → hash
group_by → enumerator
enum.c
View on GitHub ↗
static VALUE
enum_group_by(VALUE obj)
{
RETURN_SIZED_ENUMERATOR(obj, 0, 0, enum_size);
return enum_hashify(obj, 0, 0, group_by_i);
}
With a block given returns a hash:
-
Each key is a return value from the block.
-
Each value is an array of those elements for which the block returned that key.
Examples:
Example
g = (1..6).group_by {|i| i%3 } g # => {1=>[1, 4], 2=>[2, 5], 0=>[3, 6]} h = {foo: 0, bar: 1, baz: 0, bat: 1} g = h.group_by {|key, value| value } g # => {0=>[[:foo, 0], [:baz, 0]], 1=>[[:bar, 1], [:bat, 1]]}
With no block given, returns an Enumerator.