Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 692
Stan Kurilin Avatar asked Apr 26 '10 18:04

Stan Kurilin


People also ask

How do you call a parent constructor?

In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private). $obj = new OtherSubClass();

How do you call a constructor in Ruby?

In Ruby, constructors are invoked with the help of "new" keyword and a new keyword is used for creating an object of the class. The "new" keywords give an internal call to the "initialize" method and if the new has got some arguments specified, it will be passed to the initialize method.

Can we call parent class constructor?

super() can be used to invoke immediate parent class constructor.

What does Super do in Ruby?

Ruby uses the super keyword to call the superclass implementation of the current method. Within the body of a method, calls to super acts just like a call to that original method. The search for a method body starts in the superclass of the object that was found to contain the original method.


1 Answers

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

like image 193
Jörg W Mittag Avatar answered Sep 23 '22 13:09

Jörg W Mittag