0
0
Rubyprogramming~5 mins

Class variables (@@) and their dangers in Ruby

Choose your learning style9 modes available
Introduction

Class variables hold data shared by a class and all its subclasses. They let you keep track of information common to all objects of a class.

When you want to count how many objects of a class and its subclasses have been created.
When you need to share a setting or value across a class and all its subclasses.
When you want to keep track of a total or summary that applies to all instances of a class family.
Syntax
Ruby
class ClassName
  @@class_variable = value

  def some_method
    @@class_variable
  end
end

Class variables start with @@ and are shared by the class and all its subclasses.

Changing a class variable affects all classes in the inheritance chain.

Examples
This example counts all animals created, including dogs, using a class variable.
Ruby
class Animal
  @@count = 0

  def initialize
    @@count += 1
  end

  def self.count
    @@count
  end
end

class Dog < Animal
end

Dog.new
Dog.new
puts Animal.count
Changing the class variable in Child also changes it in Parent, showing shared state.
Ruby
class Parent
  @@value = 1
end

class Child < Parent
  def self.change_value
    @@value = 5
  end
end

Child.change_value
puts Parent.class_variable_get(:@@value)
Sample Program

This program counts all vehicles created, including cars and trucks, using a class variable.

Ruby
class Vehicle
  @@total_vehicles = 0

  def initialize
    @@total_vehicles += 1
  end

  def self.total_vehicles
    @@total_vehicles
  end
end

class Car < Vehicle
end

class Truck < Vehicle
end

Car.new
Car.new
Truck.new

puts Vehicle.total_vehicles
OutputSuccess
Important Notes

Class variables can cause unexpected bugs because subclasses share the same variable.

Changing a class variable in one subclass affects all other subclasses and the parent class.

Consider using class instance variables or class methods for safer, clearer sharing of data.

Summary

Class variables (@@) share data across a class and all its subclasses.

They can cause tricky bugs because all classes share the same variable.

Use them carefully or prefer safer alternatives like class instance variables.