What is the difference between a class variable and a class instance variable?
What is the difference between a class variable and a class instance variable?
In Ruby, class variables and class instance variables are both associated with a class rather than instances of the class, but they have different behaviors, particularly with regard to inheritance.
A class variable in Ruby is defined with two at signs (@@
) and is shared across the class and all of its subclasses. This means that if you change the value of a class variable in one place, it changes for all instances of the class and its subclasses. Class variables can lead to unexpected behavior due to their shared nature, especially when dealing with inheritance. If a subclass changes the value of a class variable, it will affect the superclass and all other subclasses that share this variable[1][2][3][4].
Example:
class Vehicle
@@wheels = 4
end
class Car < Vehicle
end
Car.class_variable_set(:@@wheels, 2)
Vehicle.class_variable_get(:@@wheels) # => 2, because @@wheels is shared
A class instance variable in Ruby is defined with one at sign (@
) and is not shared with subclasses. It is tied to the specific class object itself, not to instances of the class or its subclasses. Class instance variables are useful when you want to hold information that is specific to a particular class and you do not want it to be shared with subclasses[1][6][7][8].
Example:
class Vehicle
@fuel_efficiency = 30
class << self
attr_accessor :fuel_efficiency
end
end
class Car < Vehicle
@fuel_efficiency = 25
end
Vehicle.fuel_efficiency # => 30
Car.fuel_efficiency # => 25, because @fuel_efficiency is not shared
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào