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 0Create two subclasses
Dog and Cat that inherit from AnimalIncrement
@@count each time a new animal is createdPrint 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