Class instance variables as alternative
📖 Scenario: You are creating a simple program to track the number of books created in a library system. Instead of using class variables, you will use class instance variables to keep count.
🎯 Goal: Build a Ruby class Book that uses a class instance variable to count how many book objects have been created.
📋 What You'll Learn
Create a class called
BookUse a class instance variable
@count to store the number of booksCreate an
initialize method that increases @count by 1 each time a new book is createdAdd a class method
count to return the current number of booksCreate 3 book instances and print the total count using
Book.count💡 Why This Matters
🌍 Real World
Class instance variables help keep data specific to a class without sharing it with subclasses, useful in real-world applications like tracking counts or settings per class.
💼 Career
Understanding class instance variables is important for Ruby developers to write clean, maintainable code and avoid bugs related to shared class variables.
Progress0 / 4 steps