gpt4 book ai didi

ruby - 在Ruby中调用几个包含模块的 'initialize'

转载 作者:数据小太阳 更新时间:2023-10-29 09:02:13 27 4
gpt4 key购买 nike

如果我将一个模块包含到一个定义了 initialize 的类中,我可以使用 super 调用它:

module M
def initialize(x)
@m = x
end
end

class MyClass
def initialize
super(3)
end

def val
@m
end
end

MyClass.new.val
# => 3

但是,如果我有多个模块,可能还有一个父类,我该如何编写代码呢?

class Parent
def initialize(x)
@p = x
end
end

module M
def initialize(x)
@m = x
end
end

module N
def initialize(x)
@n = x
end
end

class MyClass < Parent
include M
include N
def initialize
# ???? How to initialize here?
end

def val
[@m,@n,@p]
end
end

我猜 MyClass::initialize 中的 super(100) 会设置变量 @n,因为 N 是“最近的”祖先,但是如何调用 MParent 中的 initialize 方法?

最佳答案

看看这篇博文 ( http://stdout.koraktor.de/blog/2010/10/13/ruby-calling-super-constructors-from-multiple-included-modules/ )。它解释了如何使用来自不同包含模块的 initialize

关于ruby - 在Ruby中调用几个包含模块的 'initialize',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32763168/

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