What is initialize() method in Ruby?

The initialize() method in Ruby is just like a constructor in other languages. Because the initialize() method is used at the time of instantiation or object creation. At is also used to set the initial values of an object.

Conside the following example:

            
              class Rectangle
                def initialize(length, width)
                  @length = length
                  @width = width
                end

                def area
                  @length * @width
                end

                def peremeter
                  2 * (@length + @width)
                end
              end

              # defining objects of rectangle

              @rectangle = Rectangle.new(100, 200)
              #<Rectangle:0x000000012f9e3ab0 @length=100, @width=200>

              @rectangle = Rectangle.new()
              #`initialize': wrong number of arguments (given 0, expected 2) (ArgumentError)
            
          

In the above example you can see that when you instantiate the Rectangle class with arguments then it creates the instance of it and set the initial values of @length and @width instance variables. And when you instantiate Rectangle class without any argument you will see an ArgumenrError error there. Because the initialize() method inside the Rectangle accepts two arguments.

However it is not necessary always to define initialize() method to accept arguments because if it is not required to set the initial values for an object at the time of instantiation then you can avoid this or as an option you can add default argument to your initialize() method as well.

NOTE: Since an initialize() method always return the instance of object so it does not make any sense to use the return statement within it.

APPSIMPACT Academy

Ruby on Rails is a very popular and most productive web application development framework. At APPSIMPACT Academy we provide best content to learn Ruby on Rails framework.

Questions & Answers
What is the difference between instance variables and local variables? What is initialize() method in Ruby? What are getter and setter methods in Ruby? Comparision between rails 4, 5 and 6 What is difference between sub and gsub in Ruby? How to recreate flatten method in Ruby using recursion?