call parent constructor in ruby

Stan Kurilin picture Stan Kurilin · Apr 26, 2010 · Viewed 34k times · Source

How can I call parents constructor ?

module C
    attr_accessor :c, :cc
    def initialization c, cc
        @c, @cc = c, cc
    end 
end

class B
    attr_accessor :b, :bb
    def initialization b, bb
        @b, @bb = b, bb
    end 
end


class A < B
    include C
    attr_accessor :a, :aa
    def initialization (a, b, c, aa, bb, cc)
        #call B::initialization - ?
        #call C::initialization - ?
        @a, @aa = a, aa
    end
end

Thanks.

Answer

J&#246;rg W Mittag picture Jörg W Mittag · Apr 26, 2010

Ruby doesn't have constructors, therefore it's obviously not possible to call them, parent or otherwise. Ruby does have methods, however, and in order to call the parent's method with the same name as the currently executing method, you can use the super keyword. [Note: super without arguments is a shortcut for passing the same arguments that were passed into the currently executing method. If you actually want to pass no arguments, you have to do so explicitly: super().]