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