0
0
Rubyprogramming~30 mins

Group_by for categorization in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Group_by for categorization
📖 Scenario: You work at a bookstore that wants to organize books by their genre to make it easier for customers to find what they like.
🎯 Goal: You will create a Ruby program that groups a list of books by their genre using the group_by method.
📋 What You'll Learn
Create an array of hashes called books with each book having :title and :genre keys
Create a variable called grouped_books to store the result of grouping books by genre using group_by
Print the grouped_books variable to show books categorized by genre
💡 Why This Matters
🌍 Real World
Grouping items by category is common in apps like bookstores, music libraries, or inventory systems to help users find things easily.
💼 Career
Understanding how to group data efficiently is important for software developers working with collections, databases, or data analysis.
Progress0 / 4 steps
1
Create the books array
Create an array called books with these exact hashes: { title: 'The Hobbit', genre: 'Fantasy' }, { title: '1984', genre: 'Dystopian' }, { title: 'The Catcher in the Rye', genre: 'Classic' }, { title: 'The Lord of the Rings', genre: 'Fantasy' }, { title: 'Brave New World', genre: 'Dystopian' }
Ruby
Need a hint?

Use square brackets [] to create an array and curly braces {} for each book hash.

2
Prepare to group books by genre
Create a variable called grouped_books and set it to nil for now as a placeholder.
Ruby
Need a hint?

This step sets up a variable to hold the grouped result later.

3
Group the books by genre
Use the group_by method on the books array to group books by their :genre key. Assign the result to the variable grouped_books.
Ruby
Need a hint?

Use group_by { |book| book[:genre] } to group books by genre.

4
Print the grouped books
Write a puts statement to print the grouped_books variable so you can see the books grouped by genre.
Ruby
Need a hint?

Use puts grouped_books to display the grouped result.