我正在尝试理解包含类变量的模块。我认为包含带有类变量的模块也会将类变量包含到类定义中。
这按预期工作:
module A
@@my_name = "rick"
def print_name
puts @@my_name
end
end
class Y
include A
extend A
end
Y.print_name
但这不会:
module A
def self.included(klass)
klass.include B
klass.extend C
end
module B
@@my_name = "bob"
end
module C
def print_name
puts @@my_name
end
end
end
class Y
include A
end
Y.print_name
我期待的是“bob”,但我却得到了:
uninitialized class variable @@my_name in A::C
最佳答案
如果你使用 Module#class_variable_get
就可以了:
module C
def print_name
class_variable_get(:@@my_name)
end
end
Y.print_name
#=> "bob"
我认为问题是当你在 module C
中说 puts @@my_name
它还不知道 @@my_name
,因为在 module C
中你从未设置它(它在 module B
中设置并且 C
不知道 B
).
关于Ruby 模块包含和类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41154431/