0
0
Rubyprogramming~5 mins

Initialize method as constructor in Ruby

Choose your learning style9 modes available
Introduction

The initialize method sets up a new object with starting values automatically when you create it. It helps prepare the object to be used right away.

When you want to give an object some starting information as soon as it is made.
When you want to make sure certain values are always set for an object.
When you want to avoid setting values manually after creating an object.
When you want to create many objects with different starting values easily.
Syntax
Ruby
class ClassName
  def initialize(parameters)
    # set up instance variables
  end
end

The initialize method is called automatically when you use ClassName.new.

Use @variable to store values inside the object.

Examples
This example sets a person's name when you create a new Person.
Ruby
class Person
  def initialize(name)
    @name = name
  end
end
This example sets both the make and year of a car when it is created.
Ruby
class Car
  def initialize(make, year)
    @make = make
    @year = year
  end
end
Sample Program

This program creates a Dog object with a name and breed using initialize. Then it prints the dog's details.

Ruby
class Dog
  def initialize(name, breed)
    @name = name
    @breed = breed
  end

  def info
    "Dog's name is #{@name} and breed is #{@breed}."
  end
end

dog = Dog.new("Buddy", "Golden Retriever")
puts dog.info
OutputSuccess
Important Notes

You do not call initialize directly; Ruby calls it when you create a new object.

Instance variables like @name keep data inside the object for later use.

Summary

initialize sets up new objects automatically.

It helps give objects starting values.

Use instance variables inside initialize to store data.