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

标签 ruby module mixins

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

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/

相关文章:

ruby-on-rails - AssociationType 与嵌套模型表单上的预期类型不匹配

javascript - 如何在不使用全局范围的情况下分离 angularjs 文件

perl - 安装 perl 模块时 cpan 不使用配置的存储库而是尝试连接到 cpan.org

javascript - 将模块隐藏在闭包中的原因是什么?

ruby - cucumber :何时使用标签/ Hook 与背景

ruby-on-rails - 如何找到数组中最后一项的索引?

scala - 可堆叠特征中的继承和代码重用

CSS calc() 与多个单位相乘

ruby - 创建哈希数组的组合

Scala 特征混合顺序和 super 调用