CrystalLang-Initialize Method

CrystalLang-Initialize Method

The initialize method is useful when we want to initialize some class variables at the time of object creation. The initialize method is part of the object-creation process in Crystal and it allows us to set the initial values for an object.

Below are some points about Initialize :

We can define default argument.

It will always return a new object so return keyword is not used inside initialize method.

Defining initialize keyword is not necessary if our class doesn’t require any arguments.

If we try to pass arguments into new and if we don’t define initialize we are going to get an error.

class Rectangle 
  @x = Int32
  @y = Int32

# Method with initialize keyword 
def initialize(x : Int32 , y : Int32) 

    # Initialize variable 
    @x = x 
    @y = y 
end
  def display_details() 
    puts "value of x: #{@x}"
    puts "value of y: #{@y}"

   end
end

# create a new Rectangle instance by calling 
r1 = Rectangle.new(10, 20) 
r1.display_details

output

value of x: 10

value of y: 20

Ref: geeksforgeeks.org/the-initialize-method-in-..

Code is tested at :play.crystal-lang.org/#/r/gc3o