Ruby - Constructors:new vs initialize

Introduction

The method responsible for creating an object is called the constructor.

In Ruby, the constructor method is called new.

The new method is a class method.

Once it has created an object, it will run an instance method named initialize if such a method exists.

The new method is the constructor, and the initialize method is used to initialize the values of any variables immediately after an object is created.

But why can't you just write your own new method and initialize variables in it?

Demo

class MyClass 
   def initialize( aStr ) 
      @avar = aStr # from  ww  w.ja  v a2  s.  c  om
   end 

   def MyClass.new( aStr )  
      super 
      @anewvar = aStr.swapcase 
   end 
end 

ob = MyClass.new( "hello world" ) 
puts( ob ) 
puts( ob.class )

Result

Here, MyClass.new method begins with the super keyword to invoke the new method of its superclass.

Then it created a string instance variable, @anewvar.

The last expression evaluated by a method in Ruby is the value returned by that method.

The last expression evaluated by the new method here is a string. I evaluate this:

Overriding new is confusing and is generally a bad idea.

Related Topic