Class variables are an essential feature in Ruby's object-oriented programming paradigm. They allow data to be shared across all instances of a class, providing a way to maintain state at the class level.
In Ruby, class variables are prefixed with @@
and are accessible to all instances of a class. They differ from instance variables, which are unique to each object.
To define a class variable, use the following syntax:
class MyClass
@@class_variable = initial_value
end
Class variables can be accessed and modified within instance methods, class methods, and the class definition itself.
class Person
@@person_count = 0
def initialize(name)
@name = name
@@person_count += 1
end
def self.total_count
@@person_count
end
end
person1 = Person.new("Alice")
person2 = Person.new("Bob")
puts Person.total_count # Output: 2
In this example, @@person_count
keeps track of the total number of Person
instances created.
class DatabaseConnection
@@config = { host: 'localhost', port: 5432 }
def self.config
@@config
end
def self.update_config(new_config)
@@config.merge!(new_config)
end
end
puts DatabaseConnection.config
# Output: {:host=>"localhost", :port=>5432}
DatabaseConnection.update_config({ port: 3306 })
puts DatabaseConnection.config
# Output: {:host=>"localhost", :port=>3306}
Here, @@config
stores shared configuration settings for database connections.
Class variables play a crucial role in Ruby's object-oriented design. They complement instance variables and constants, offering a way to maintain state at the class level. This feature is particularly useful when implementing design patterns or managing shared resources across multiple instances.
Ruby class variables provide a powerful mechanism for sharing data across all instances of a class. While they offer unique capabilities, it's important to use them judiciously and be aware of their behavior in complex class hierarchies. Mastering class variables will enhance your ability to design efficient and maintainable Ruby programs.