如何在不扩展模块的情况下在类方法中使用模块方法?
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
仅仅因为评论字符太少,但同意maegar:
module TestModule
def module_method
"module"
end
end
class TestClass
def self.testSelfMethod
str = module_method + " from class"
puts str
end
def testSelfMethod
str = module_method + " from instance"
puts str
end
end
TestClass.extend TestModule
TestClass.testSelfMethod # => module from class
TestClass.include TestModule
TestClass.new.testSelfMethod # => module from instance