我们如何在不扩展模块的情况下在类方法中使用模块方法?
module TestModule
def module_method
"module"
end
end
class TestClass
include TestModule
def self.testSelfMethod
str = module_method
puts str
end
TestClass.testSelfMethod
end
然后它返回:
test.rb:11:in `testSelfMethod': undefined local variable or method `module_method' for TestClass:Class (NameError)
最佳答案
通过包含模块,您使 module_method
成为 TestClass
上的实例 方法,这意味着您需要在类,而不是类本身。
如果你想让它成为类本身的一个方法,你需要extend TestModule
,而不是include
。
module TestModule
def module_method
"module"
end
end
class TestClass
extend TestModule # extend, not include
def self.testSelfMethod
str = module_method
puts str
end
TestClass.testSelfMethod # "method"
end
关于Ruby:在类方法中使用模块方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52225820/