2

I have a class that inherits from another. When calling the constructor in the child it is making a call to the parent, which makes a call to a method. For me that should work perfectly fine but I get an exception. The ruby code looks like:

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

When running that code I get an undefined method exception as below, but the right output is printed. Can someone please explain why?

/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]

1 Answer 1

7

In ruby super means calls superclass implementation of the current method - it is not, unlike some languages a mechanism for calling arbitrary methods from the base class.

super.writeFoo

Calls the superclass implantation of the current method (ie writeFoo) and then calls writeFoo on the result of that (hence the error).

Sign up to request clarification or add additional context in comments.

2 Comments

I'm not sure that is the problem here. The writeFoo in the child class works fine. It's the call to writeFoo from initialize that is causing the problem and I can't see why. Everything outputs correctly but I don't understand the error message in this case.
It is causing the problem. You're calling nil.writeFoo (because that is what the call to super is returning). Change it to just 'super' and you should be ok.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.