0
0
Rubyprogramming~30 mins

Comparable module usage in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the Comparable Module in Ruby
📖 Scenario: You are creating a simple program to compare different books by their number of pages. This helps readers decide which book is longer or shorter.
🎯 Goal: Build a Ruby class Book that uses the Comparable module to compare books by their page count.
📋 What You'll Learn
Create a Book class with title and pages attributes
Include the Comparable module in the Book class
Define the <=> method to compare books by their pages
Create at least two Book objects with exact titles and page counts
Use comparison operators like < and == to compare the books
Print the comparison results exactly as instructed
💡 Why This Matters
🌍 Real World
Comparing objects like books, products, or events by certain attributes is common in apps and websites to help users make choices.
💼 Career
Understanding how to use modules like Comparable helps you write cleaner, reusable code and is a valuable skill for Ruby developers.
Progress0 / 4 steps
1
Create the Book class with attributes
Create a Ruby class called Book with an initialize method that takes title and pages as parameters and sets them as instance variables.
Ruby
Need a hint?

Use def initialize(title, pages) and set @title and @pages inside.

2
Include Comparable and define spaceship operator
Inside the Book class, include the Comparable module and define the <=> method to compare Book objects by their pages attribute.
Ruby
Need a hint?

Use include Comparable and define def <=>(other) to compare pages.

3
Create Book objects and compare them
Create two Book objects named book1 with title 'Ruby Basics' and pages 150, and book2 with title 'Advanced Ruby' and pages 200. Then, use book1 < book2 and book1 == book2 to compare them and store the results in variables is_shorter and is_equal respectively.
Ruby
Need a hint?

Create book1 and book2 with exact titles and pages, then compare using < and ==.

4
Print the comparison results
Print the values of is_shorter and is_equal exactly as shown: first print is_shorter, then print is_equal on the next line.
Ruby
Need a hint?

Use puts is_shorter and puts is_equal to print the results.