在Ruby中,類變量是屬于類的,而不是屬于實(shí)例的。這意味著所有實(shí)例共享相同的類變量。為了避免誤用類變量,可以采取以下措施:
class MyClass
def initialize
@instance_variable = "Instance variable"
end
end
class MyClass
@@class_variable = "Class variable"
def self.class_method
puts @@class_variable
end
end
attr_reader
和attr_writer
:如果需要為類變量提供訪問(wèn)器(getter)和修改器(setter),可以使用attr_reader
和attr_writer
方法。這樣可以確保對(duì)類變量的訪問(wèn)和修改是受控的。class MyClass
@@class_variable = "Class variable"
attr_reader :class_variable_reader
attr_writer :class_variable_writer
def initialize
@class_variable = "Instance variable"
end
end
initialize
方法:在自定義的initialize
方法中,確保對(duì)類變量的訪問(wèn)和修改是受控的。class MyClass
@@class_variable = "Class variable"
def initialize
# Do not access or modify class variables directly here
end
end
module MyModule
MY_VARIABLE = "Shared variable"
end
class MyClass
def self.my_method
puts MyModule::MY_VARIABLE
end
end
遵循這些建議,可以避免在Ruby中誤用類變量。