我有一个从另一个继承的类。在子级调用构造函数时,它正在调用父级,父级调用一个方法。对我来说,这应该工作得很好,但我得到了一个例外。红宝石代码如下所示:
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]