0
0
Rubyprogramming~30 mins

Extend for class methods in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Extend a Module for Class Methods in Ruby
📖 Scenario: You are building a simple Ruby program to track books in a library. You want to add a feature that counts how many books have been created.
🎯 Goal: Create a module with a class method to count books. Then extend this module for class methods in the Book class.
📋 What You'll Learn
Create a module called BookCounter with a class method count that returns the number of books.
Create a class called Book.
Extend the BookCounter module for class methods in the Book class.
Create a class variable @@book_count in Book to track the number of books.
Increment @@book_count each time a new Book object is created.
Use the count class method to print the total number of books.
💡 Why This Matters
🌍 Real World
Counting objects like books, users, or orders is common in software to track totals or inventory.
💼 Career
Understanding how to add class methods via modules and track shared data is useful for Ruby developers building maintainable code.
Progress0 / 4 steps
1
Create the Book class with a class variable
Create a class called Book with a class variable @@book_count set to 0. Also, define an initialize method that increments @@book_count by 1 each time a new book is created.
Ruby
Need a hint?

Use @@book_count to keep track of the number of books. Increment it inside initialize.

2
Create the BookCounter module with a class method
Create a module called BookCounter with a class method count that returns the value of @@book_count from the Book class.
Ruby
Need a hint?

Use Book.class_variable_get(:@@book_count) inside the count method to access the class variable.

3
Extend BookCounter for class methods in Book
Extend the BookCounter module for class methods in the Book class using extend BookCounter.
Ruby
Need a hint?

Use Book.extend BookCounter after the class and module definitions to add class methods to Book.

4
Create books and print the total count
Create three Book objects named book1, book2, and book3. Then print the total number of books using Book.count.
Ruby
Need a hint?

Create three books with Book.new and print the count with puts Book.count.