Ruby:在类方法中使用模块方法 [英] Ruby: Use module method inside a class method

查看:72
本文介绍了Ruby:在类方法中使用模块方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do we use a module method inside a class method without extending the module?

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实例 方法code>,这意味着您需要在类的实例上调用它,而不是类本身.

By including the module, you make module_method is an instance method on TestClass, meaning you need to invoke it on an instance of the class, not the class itself.

如果你想让它成为类本身的方法,你需要扩展TestModule,而不是include它.

If you want to make it a method on the class itself, you need to 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

这篇关于Ruby:在类方法中使用模块方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆