2
다른 클래스에서 상속받은 클래스가 있습니다. 자식에서 생성자를 호출 할 때 부모에게 전화를 걸면 메서드가 호출됩니다. 나를 위해 완벽하게 잘 작동해야하지만 예외가 있습니다. 루비 코드는 다음과 같습니다.루비에서 initialize 메소드를 호출 할 때 정의되지 않은 메소드
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
해당 코드를 실행할 때 아래와 같은 정의되지 않은 예외가 발생하지만 올바른 출력이 인쇄됩니다. 누군가 이유를 설명해 주시겠습니까? 루비 super
에서
/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]
여기에 문제가 있는지 잘 모르겠습니다. 자식 클래스의'writeFoo'는 잘 동작합니다. 문제를 일으키는'initialize'에서'writeFoo'를 호출 한 것입니다. 왜 그런지 볼 수 없습니다. 모든 것이 올바르게 출력되지만이 경우에는 오류 메시지를 이해할 수 없습니다. –
문제의 원인입니다. nil.writeFoo를 호출하고 있습니다 (super에 대한 호출이 반환하기 때문에). 그냥 '슈퍼'로 바꾸면 괜찮을거야. –
이제 무슨 뜻인지 알 겠어. 너는 완전히 옳다. 감사! –