What is Class Variable in Ruby: Explanation and Examples
class variable is a variable shared among a class and all its instances, defined with @@ prefix. It stores data common to the class itself and every object created from it.How It Works
A class variable in Ruby is like a shared notebook that everyone in a group can read and write to. Imagine a classroom where the teacher and all students can see and update the same whiteboard. This whiteboard holds information that applies to the whole class, not just one student.
In Ruby, class variables start with @@ and belong to the class itself, not just one object. When you change a class variable, the change is visible to all instances of that class and the class itself. This helps keep track of data that should be common, like counting how many objects have been created.
Example
This example shows a class variable @@count that counts how many objects of the class have been made.
class Dog @@count = 0 def initialize(name) @name = name @@count += 1 end def self.count @@count end end dog1 = Dog.new("Buddy") dog2 = Dog.new("Max") puts Dog.count
When to Use
Use class variables when you want to share information across all instances of a class. For example, tracking how many objects have been created, storing configuration settings for all objects, or keeping a shared cache.
However, be careful because class variables are shared by the class and all subclasses, which can sometimes cause unexpected changes if subclasses modify them. For safer sharing, Ruby also offers class instance variables or constants.
Key Points
- Class variables start with
@@and are shared by the class and all its instances. - They hold data common to all objects of the class.
- Changes to class variables affect all instances and subclasses.
- Use them for shared counters, settings, or caches.
- Be cautious with inheritance as subclasses share the same class variable.