Ruby | Enumerable group_by() function

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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

Example #2:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

{2=>[2, 8], 3=>[9], 4=>[10], 5=>[23]}


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.