call parent constructor in ruby call parent constructor in ruby ruby ruby

call parent constructor in ruby


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


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  endendmodule Cendclass 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  endenda = A.new(1,2,3,4)puts a.inspect # => #<A:0x42d6d8 @aa=3, @a=1, @b=2, @bb=4>


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.