Skip to content
Related Articles

Related Articles

Ruby | Enumerable group_by() function
  • Last Updated : 05 Dec, 2019

The group_by() of enumerable is an inbuilt method in Ruby returns an hash where the groups are collectively kept as the result of the block after grouping them. In case no block is given, then an enumerator is returned.

Syntax: enu.group_by { |obj| block }

Parameters: The function takes an optional block according to which grouping is done.

Return Value: It returns a hash.

Example #1:






# Ruby program for group_by method in Enumerable
  
# Initialize 
enu = (1..10)
  
# Prints
enu.group_by { |obj| obj % 4 == 1 }


Output:

{true=>[1, 5, 9], false=>[2, 3, 4, 6, 7, 8, 10]}

Example #2:




# Ruby program for group_by method in Enumerable
  
# Initialize 
enu = [2, 8, 9, 10, 23]
  
# Prints
enu.group_by { |obj| obj % 6 }


Output:

{2=>[2, 8], 3=>[9], 4=>[10], 5=>[23]}
My Personal Notes arrow_drop_up
Recommended Articles
Page :