是否可以从也在该模块中的类内部调用Module函数

Rya*_*arn 5 ruby

在这个Ruby代码中:

Module M
  Class C < Struct.new(:param)
    def work
      M::helper(param)
    end
  end

  def helper(param)
    puts "hello #{param}"
  end
end
Run Code Online (Sandbox Code Playgroud)

当我尝试运行时,我得到一个"未定义的方法'帮助'''M:模块'"错误

c = M::C.new("world")
c.work
Run Code Online (Sandbox Code Playgroud)

M::helper("world")直接从另一个班级调用工作正常.类可以不调用在它们定义的同一模块中定义的模块函数吗?除了将课程移到模块之外之外,还有其他方法吗?

Gis*_*shu 6

为了调用,M::helper您需要将其定义为def self.helper; end 为了进行比较,请查看以下修改后的代码片段中的 helper 和 helper2

module M
  class C < Struct.new(:param)
    include M     # include module to get helper2 mixed in
    def work
      M::helper(param)
      helper2(param)
    end
  end

  def self.helper(param)
    puts "hello #{param}"
  end

  def helper2(param)
    puts "Mixed in hello #{param}"
  end
end

c = M::C.new("world")
c.work
Run Code Online (Sandbox Code Playgroud)