The Initialize Method in Ruby

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 Ruby 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.

Syntax:



def initialize(argument1, argument2, .....)

Without Initialize variable –

Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program of Initialize method
class Geeks
  
  # Method with initialize keyword
  def initialize(name)
  end
end

chevron_right


Output :

=> :initialize

In above example, we add a method called initialize to the class, method have a single argument name. using initialize method will initialize a object.

With Initialize Variable –

Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program of Initialize method
class Rectangle
  
  # Method with initialize keyword
  def initialize(x, y)
  
    # Initialize variable
    @x = x
    @y = y
  end
end
  
# create a new Rectangle instance by calling 
Rectangle.new(10, 20)

chevron_right


Output :

#<Rectangle:0x0000555e7b1ba0b0 @x=10, @y=20>

In above example, Initialize variable are accessed using the @ operator within the class but to access them outside of the class we will use public methods.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.