Ruby:在类方法中使用模块方法

问题描述 投票:0回答:2

如何在不扩展模块的情况下在类方法中使用模块方法?

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)
ruby module mixins
2个回答
2
投票

通过包含该模块,您可以使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

0
投票

仅仅因为评论字符太少,但同意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
© www.soinside.com 2019 - 2024. All rights reserved.