获取对ruby中封闭模块的引用
如何在ruby中获得对封闭模块的引用获取对ruby中封闭模块的引用,ruby,Ruby,如何在ruby中获得对封闭模块的引用 module Foo @@variable=1 def variable @@variable end class A def somemethod puts "variable=#{Foo.variable}" #<--this won't run, resolving Foo # as the c
module Foo
@@variable=1
def variable
@@variable
end
class A
def somemethod
puts "variable=#{Foo.variable}" #<--this won't run, resolving Foo
# as the class instead of the module
end
end
class Foo
... # doesn't matter what's here
end
end
模块Foo
@@变量=1
def变量
@@变数
结束
甲级
定义方法
放置“variable={Foo.variable}”#您可以通过将:
前缀添加到Foo
:
::Foo.variable
在您的示例代码中:
module Foo
@@variable=1
def variable
@@variable
end
class A
def somemethod
puts "variable=#{::Foo.variable}"
end
end
class Foo
... # doesn't matter what's here
end
end
当我尝试它时,我从foo.rb:31:in中得到:`foo.rb:14:insomemethod:undefined method
variable',用于foo:Module(NoMethodError)
中的foo.rb:14:indef self.variable