Câu hỏi phỏng vấn Ruby
Câu hỏi

What is the difference between a class variable and a class instance variable?

Câu trả lời

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.

Class Variable

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

Class Instance Variable

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

Key Differences

  • **Inh...
junior

junior

Gợi ý câu hỏi phỏng vấn

middle

What is the difference between Module#remove_method and Module#undef_method ?

middle

What is the difference between Kernel#require and Kernel#load ?

entry

Which core object includes the "Kernel" module?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào