我们如何在类方法中使用模块方法而不扩展模块?
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
is an instance方法上TestClass
,这意味着您需要在类的实例上调用它,而不是类本身。
如果你想让它成为类本身的方法,你需要extend TestModule
, not include
it.
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)