0
0
Rubyprogramming~30 mins

Class variables (@@) and their dangers in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Class variables (@@) and their dangers
📖 Scenario: Imagine you are creating a simple program to track how many animals have been created in a zoo. You want to use a class variable to count all animals, but you will see why this can cause problems when you have different types of animals.
🎯 Goal: You will build a Ruby program that uses a class variable @@count to count animals created in different subclasses. You will observe how the class variable is shared and why this can be dangerous.
📋 What You'll Learn
Create a base class Animal with a class variable @@count initialized to 0
Create two subclasses Dog and Cat that inherit from Animal
Increment @@count each time a new animal is created
Print the total count of animals after creating some dogs and cats
💡 Why This Matters
🌍 Real World
Class variables are sometimes used to keep track of shared data like counts or settings across related classes in programs.
💼 Career
Understanding class variables and their pitfalls helps you write safer, clearer Ruby code, which is important for software development jobs using Ruby.
Progress0 / 4 steps
1
Create the base class with class variable
Create a class called Animal with a class variable @@count set to 0. Add an initialize method that increases @@count by 1 each time an animal is created.
Ruby
Need a hint?

Use @@count to store the count and increase it inside initialize.

2
Create subclasses Dog and Cat
Create two subclasses called Dog and Cat that inherit from Animal. Add empty initialize methods that call super to use the base class initialization.
Ruby
Need a hint?

Use class Dog < Animal and class Cat < Animal. Inside initialize, call super.

3
Create some animals
Create two Dog objects and three Cat objects by calling their constructors.
Ruby
Need a hint?

Create objects by calling Dog.new and Cat.new.

4
Print the total animal count
Print the total number of animals created using @@count from the Animal class.
Ruby
Need a hint?

Define a class method self.count to return @@count. Then print it.