Skip to content

End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Enumerable#group_by

enum.group_by { |obj| block } → a_hash
enum.group_by → an_enumerator

Groups the collection by result of the block. Returns a hash where the keys are the evaluated result from the block and the values are arrays of elements in the collection that correspond to the key.

If no block is given an enumerator is returned.

Example
(1..6).group_by { |i| i%3 }   #=> {0=>[3, 6], 1=>[1, 4], 2=>[2, 5]}
See also #grep_v #include? #grep #inject also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.1