DEV Community

roeihaviv
roeihaviv

Posted on

The 'initialize' method

The 'initialize' method is a special method that gets called automatically when an object is created from a class. It is used to set the initial state of the object. The initialize method is defined within the class definition and is typically used to accept and set attributes of the object.

For example, a class Person might have an initialize method that takes in a name and age, and sets those as attributes of the object:

--

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

person = Person.new("John", 30)
puts person.inspect

--

In this example, when Person.new("John", 30) is called, it automatically calls the initialize method, which sets @name to "John" and @age to 30. The inspect method is called on the object, which will display the instance variables and their values.

Top comments (0)