views:

486

answers:

3

Hi! 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.

+2  A: 

Use the super method! Ruby does not have multiple inheritance though.

class B

  attr_accessor :b, :bb

  def initialize(b, bb)
    @b, @bb = b, bb
  end

end

module C

end

class A < B
  include C  # <= if C was a class, you'd get: TypeError: wrong argument type Class (expected Module)

  attr_accessor :a, :a

  def initialize(a,b,aa,bb)
    @a, @aa = a, aa
    super(b, bb)  # <= calls B#initialize
  end

end

a = A.new(1,2,3,4)
puts a.inspect # => #<A:0x42d6d8 @aa=3, @a=1, @b=2, @bb=4>
macek
+4  A: 

First, your method should be initialize, not initialization. Then, you can use super to call the parent class method. As for calling C's initializer in A, for clarity, I'd recommend splitting the initialization stuff into a different function, then just calling that function directly. It's easy to implement, and clearer.

Peter
+1  A: 

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().]

Jörg W Mittag
@Jörg, +1. Thanks for the mention of the shortcut. Overriding methods just became so much more elegant :)
macek