How to Use the Initialize Method in Ruby



In this article, you will learn how to use the initialize method in Ruby.

The Initialize Method

In Ruby, the initialize method is a special method that gets called automatically when a new object is created from a class. It is used to initialize the object’s instance variables with some default or user-specified values. Here’s how to use the initialize method in Ruby:

Define a class

First, you need to define a class. For example, let’s create a Person class:

class Person
  # code for Person class

Define the initialize method

Inside the class, define the initialize method. This method takes any number of arguments, and you can use these arguments to initialize the instance variables. For example:

class Person
  def initialize(name, age)
    @name = name
    @age = age

In the above code, we defined the initialize method to take two arguments, name and age. We then use these arguments to set the instance variables @name and @age.

Create an object

To create a new object of the Person class, you simply call the new method and pass in the required arguments:

person ="Alice", 25)

In the above code, we created a new Person object and passed in the values for name and age.

Access instance variables

Once the object is created, you can access its instance variables using the @ symbol:

puts person.@name # prints "Alice"
puts person.@age # prints 25

In the above code, we accessed the instance variables @name and @age of the person object.