gpt4 book ai didi

ruby - 从ruby中的初始化调用方法时未定义的方法

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

我有一个继承自另一个的类。当在子级中调用构造函数时,它正在调用父级,父级调用一个方法。对我来说应该工作得很好但我得到一个异常(exception)。 ruby 代码如下所示:

class MyTestClass
def initialize
@foo = "hello world"
puts "init parent"
writeFoo
end

def writeFoo
puts @foo + " from base"
end
end

class MySubClass < MyTestClass
def initialize
puts "init sub"
super
end

def writeFoo
puts @foo + " from sub"
super.writeFoo
end
end

@foo = MySubClass.new

当运行该代码时,我得到一个未定义的方法异常,如下所示,但打印了正确的输出。谁能解释一下为什么?

/Users/tj/dev/coursera/sml/hw6/test.rb:21:in `writeFoo': undefined method `writeFoo' for nil:NilClass (NoMethodError)
from /Users/tj/dev/coursera/sml/hw6/test.rb:5:in `initialize'
from /Users/tj/dev/coursera/sml/hw6/test.rb:16:in `initialize'
from /Users/tj/dev/coursera/sml/hw6/test.rb:25:in `new'
from /Users/tj/dev/coursera/sml/hw6/test.rb:25:in `<main>'
init sub
init parent
hello world from sub
hello world from base
[Finished in 0.1s with exit code 1]

最佳答案

在 ruby​​ 中,super 意味着调用当前方法的父类(super class)实现 - 与某些语言不同,它不是从基类调用任意方法的机制。

super.writeFoo

调用当前方法的父类(super class)植入(即 writeFoo),然后对其结果调用 writeFoo(因此出错)。

关于ruby - 从ruby中的初始化调用方法时未定义的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15309088/

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