gpt4 book ai didi

ruby - 如何在 ruby​​ 模块之间共享方法

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

这是我尝试过的:

module A
def self.method1; "method1"; end
def method2; "method2"; end
end

module B; include A; end

B.method1 # => error
B.method2 # => error
B::method1 # => error
B::method2 # => error

我想避免在两个模块之间复制和粘贴等效代码。我在这里使用模块而不是类的原因是因为我不需要每个模块的多个实例,因为它们只是保持常量(此时是其他模块)。

解决这个问题的最佳方法是什么?

最佳答案

Plain include 只为您提供实例方法(method2 在您的特定代码段中)。如果您想共享模块级方法 - 将它们提取到单独的模块并使用它扩展其他模块:

module A
extend self # to be able to use A.method1

def method1
"method1"
end
end

module B
extend A
end

B.method1 # => "method1"

也可以通过 include 获取模块级方法,但有一点变化,使用 hook 方法:

module A
def self.included(other)
other.extend ModuleMethods # this is where the magic happens
end

def instance_method
'instance method'
end

module ModuleMethods
def module_method
'module method'
end
end

extend ModuleMethods # to be able to use A.module_method
end


module B
include A
end

B.module_method #=> "module method"
B.instance_methods #=> [:instance_method]

关于ruby - 如何在 ruby​​ 模块之间共享方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7266110/

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