0
0
Rubyprogramming~30 mins

Class instance variables as alternative in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
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 Book
Use a class instance variable @count to store the number of books
Create an initialize method that increases @count by 1 each time a new book is created
Add a class method count to return the current number of books
Create 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
1
Create the Book class with a class instance variable
Create a class called Book and inside it, create a class instance variable @count and set it to 0.
Ruby
Need a hint?

Class instance variables start with @ but are defined directly inside the class, not inside methods.

2
Add an initialize method to increase @count
Inside the Book class, add an initialize method that increases the class instance variable @count by 1 each time a new book is created. Use self.class.instance_variable_set and self.class.instance_variable_get to update @count.
Ruby
Need a hint?

Use self.class.instance_variable_get(:@count) to read and self.class.instance_variable_set(:@count, new_value) to update the class instance variable.

3
Add a class method count to return the number of books
Add a class method called count inside the Book class that returns the value of the class instance variable @count. Use instance_variable_get to access @count.
Ruby
Need a hint?

Class methods start with self. and can access class instance variables directly.

4
Create 3 books and print the total count
Create 3 instances of the Book class named book1, book2, and book3. Then print the total number of books by calling Book.count.
Ruby
Need a hint?

Creating each new Book.new calls initialize which increases the count. Use puts Book.count to print the total.