0
0
Rubyprogramming~5 mins

Group_by for categorization in Ruby

Choose your learning style9 modes available
Introduction

Group_by helps you sort items into groups based on a rule you choose. It makes it easy to organize data by categories.

You want to separate a list of people by their age groups.
You have a list of words and want to group them by their first letter.
You want to organize sales records by the month they happened.
You need to group animals by their species from a list.
Syntax
Ruby
collection.group_by { |item| condition }

The group_by method takes a block with a rule to decide the group for each item.

It returns a hash where keys are group names and values are arrays of items in those groups.

Examples
This groups numbers into even and odd using n.even? as the condition.
Ruby
numbers = [1, 2, 3, 4, 5, 6]
groups = numbers.group_by { |n| n.even? }
# => {false=>[1, 3, 5], true=>[2, 4, 6]}
This groups words by their first letter.
Ruby
words = ['apple', 'banana', 'avocado', 'blueberry']
groups = words.group_by { |w| w[0] }
# => {'a'=>['apple', 'avocado'], 'b'=>['banana', 'blueberry']}
Sample Program

This program groups fruits by their first letter and prints each group with its fruits.

Ruby
fruits = ['apple', 'banana', 'apricot', 'blueberry', 'avocado']
groups = fruits.group_by { |fruit| fruit[0] }

groups.each do |letter, fruit_list|
  puts "Fruits starting with '#{letter}':"
  fruit_list.each { |fruit| puts "- #{fruit}" }
end
OutputSuccess
Important Notes

Group_by does not change the original collection.

The keys in the result hash come from the values returned by the block.

Summary

Group_by helps organize items into categories easily.

It returns a hash with groups as keys and arrays of items as values.

Use it when you want to sort data by a shared property.