[英]How do I initialize a class variable in Ruby?
For instance: 例如:
class MyClass
@@var1 = '123456'
def self.var1
@@var1
end
class << self
attr_accessor :var2
def self.initialize
self.var2 = 7890
end
end
end
p MyClass.var1 # "123456"
p MyClass.var2 # nil
Is there any way to initialize var2? 有什么办法初始化var2吗?
You could do this if var2 is not a boolean. 如果var2不是布尔值,则可以执行此操作。
class MyClass
class << self
attr_writer :var2
end
def self.var2
@@var2 ||= 'my init value'
end
end
First of all, here's a confusion in class variable and singleton class. 首先,这是类变量和单例类的混淆。 When you're doing
class << self
it doesn't mean you can now get @@var1
as self.var1
. 当您在做
class << self
时,并不意味着您现在可以将@@var1
作为self.var1
。 I illustrate it by this example 我通过这个例子来说明
class MyClass
@@var1 = '123456'
class << self
attr_accessor :var1
def get_var1
@@var1
end
def set_var1
self.var1 = '654321'
end
end
end
MyClass.get_var1 #=> '123456'
MyClass.set_var1 #=> '654321'
MyClass.get_var1 #=> '123456'
As you can see @@var1 is available in the whole class scope but it differs from singleton variable. 如您所见,@@ var1在整个类范围内可用,但与单例变量不同。
A class variable is shared among all objects of a class, and it is also accessible to the class methods. 类变量在类的所有对象之间共享,并且类方法也可以访问它。 So you can initialize it in any place you find it acceptable.
因此,您可以在任何可以接受的地方对其进行初始化。 The most simple and understandable is right in the class scope.
最简单易懂的是在类范围内。
class MyClass
@@var1 = '123456'
...
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.