【问题标题】:included module methods cant be called in class methods包含的模块方法不能在类方法中调用
【发布时间】:2012-12-07 10:32:16
【问题描述】:

我有一个模块RegexHelper,其中包含验证字符串是否仅为数字的方法:

module RegexHelper
  def is_numeric?(str)
    !!str.match(/^[0-9]+$/)
  end
end

我将这个模块包含在几个类中,当我尝试在实例方法中使用它们时效果很好。但是现在我想在类方法中使用它们,即使调用RegexHelper.is_numeric?(my_str) 也不适合我。

我认为问题可能是include RegeHelper 在创建新对象时被执行。那么我怎样才能让整个班级都可以使用呢?

【问题讨论】:

    标签: ruby-on-rails ruby regex include


    【解决方案1】:

    试试这个:

    extend RegeHelper
    

    include 用于向类添加实例方法,extend 用于添加类方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-19
      • 1970-01-01
      • 2015-07-11
      相关资源
      最近更新 更多