Stan Kurilin
Stan Kurilin

Reputation: 15792

call parent constructor in ruby

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.

Upvotes: 33

Views: 40477

Answers (4)

maček
maček

Reputation: 77786

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, :aa

  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>

Upvotes: 38

parzival
parzival

Reputation: 1626

This code below will print :

A.proc1 B.proc1 C.proc1

module A
  def proc1
    puts "A.proc1"
    super
  end
end

class B
  def proc1
    puts "B.proc1"
  end
end

class C < B
  include A
  def proc1
    super
    puts "C.proc1"
  end
end

C.new.proc1

Upvotes: 8

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369556

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

Upvotes: 45

Peter
Peter

Reputation: 132317

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.

Upvotes: 28

Related Questions