我有一个带有类变量的模块
module Abc
@@variable = "huhu"
def self.get_variable
@@variable
end
class Hello
def hola
puts Abc.get_variable
end
end
end
a = Abc::Hello.new
a.hola
是否可以在不使用@@variable
方法的情况下在Hello
内获取get_variable
?我的意思是像Abc.variable
这样的东西会很好。好奇。
答案 0 :(得分:4)
您无法在模块@@variable
中Abc.variable
类的范围内直接访问Hello
(即Abc
)。为什么?因为,当Ruby解释器看到像Abc.variable
这样的东西时,它会认为variable
是Abc的类/模块方法。
在Ruby中进行编程时,重要的是要考虑Ruby方式。
答案 1 :(得分:-1)
试试这个
Abc.class_variable_get(:variable)