How to Use Class Variable in Ruby: Syntax and Examples
In Ruby, a
class variable is defined with @@ and is shared among a class and all its subclasses. You declare it inside the class and access or modify it using class or instance methods with @@variable_name.Syntax
A class variable in Ruby starts with @@. It is declared inside a class and shared by the class and all its subclasses. You can read or change it inside instance or class methods.
- @@variable_name: The class variable itself.
- Inside class or instance methods: Access or modify the variable.
ruby
class MyClass @@class_variable = 0 def self.read_variable @@class_variable end def increment_variable @@class_variable += 1 end end
Example
This example shows how a class variable @@count keeps track of how many objects of the class have been created. Both instance and class methods access and update it.
ruby
class Counter @@count = 0 def initialize @@count += 1 end def self.count @@count end end obj1 = Counter.new obj2 = Counter.new puts Counter.count
Output
2
Common Pitfalls
Class variables are shared across the class and all subclasses, which can cause unexpected changes if subclasses modify them. Also, they are not thread-safe and can lead to bugs in concurrent code.
Another common mistake is confusing class variables with instance variables or class instance variables, which behave differently.
ruby
class Parent @@var = 'parent' def self.var @@var end end class Child < Parent @@var = 'child' end puts Parent.var # Outputs 'child' because @@var is shared
Output
child
Quick Reference
- Declare: Use
@@variable_nameinside class. - Access: Use
@@variable_namein instance or class methods. - Shared: Same value for class and all subclasses.
- Beware: Changes affect all subclasses.
Key Takeaways
Class variables start with @@ and are shared by a class and its subclasses.
You can access or modify class variables inside instance or class methods.
Changes to class variables affect the class and all its subclasses.
Be careful using class variables in inheritance to avoid unexpected side effects.
Class variables are not thread-safe and should be used cautiously in concurrent code.