0
0
Rubyprogramming~30 mins

Sort_by for custom sorting in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Sort_by for custom sorting
📖 Scenario: You work in a bookstore. You have a list of books with their titles and number of pages. You want to sort the books by their page count to help customers find shorter or longer books easily.
🎯 Goal: Build a Ruby program that sorts a list of books by their page count using sort_by.
📋 What You'll Learn
Create an array of hashes called books with exact entries for title and pages
Create a variable called max_pages with the value 300
Use sort_by on books to sort by the number of pages
Print the sorted list of book titles and their page counts
💡 Why This Matters
🌍 Real World
Sorting lists of items by a property is common in apps like bookstores, libraries, or online shops to help users find what they want quickly.
💼 Career
Knowing how to use sort_by for custom sorting is a basic but important skill for Ruby developers working with collections of data.
Progress0 / 4 steps
1
Create the books array
Create an array called books with these exact hashes: { title: 'Ruby Basics', pages: 150 }, { title: 'Advanced Ruby', pages: 320 }, { title: 'Rails Guide', pages: 280 }, { title: 'JavaScript Essentials', pages: 200 }
Ruby
Need a hint?
Remember to create an array with hashes inside, each hash having keys :title and :pages.
2
Add max_pages variable
Create a variable called max_pages and set it to 300
Ruby
Need a hint?
Just create a variable named max_pages and assign 300 to it.
3
Sort books by pages using sort_by
Use sort_by on books to create a new array called sorted_books sorted by the :pages key
Ruby
Need a hint?
Use sort_by with a block that returns book[:pages].
4
Print the sorted books
Use a for loop with variable book to iterate over sorted_books and print each book's title and pages in the format: "Title: Ruby Basics, Pages: 150"
Ruby
Need a hint?
Use a for loop and puts with string interpolation to print each book's details.