gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:11:50 25 4
gpt4 key购买 nike

在这段 Ruby 代码中:

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

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

当我尝试运行时出现“'M:Module' 的未定义方法'helper'”错误

c = M::C.new("world")
c.work

但直接从另一个类调用 M::helper("world") 工作正常。类不能调用在定义它们的同一模块中定义的模块函数吗?除了将类移出模块外,还有其他解决方法吗?

最佳答案

为了调用M::helper,你需要将它定义为def self.helper;结束为了进行比较,请查看以下修改后的代码段中的 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

关于ruby - 是否可以从也在该模块中的类内部调用模块函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3159797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com