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:
enu = ( 1 .. 10 )
enu.group_by { |obj| obj % 4 == 1 }
|
Output:
{true=>[1, 5, 9], false=>[2, 3, 4, 6, 7, 8, 10]}
Example #2:
enu = [ 2 , 8 , 9 , 10 , 23 ]
enu.group_by { |obj| obj % 6 }
|
Output:
{2=>[2, 8], 3=>[9], 4=>[10], 5=>[23]}
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...