0
0
RubyConceptBeginner · 3 min read

What is the initialize Method in Ruby: Simple Explanation and Example

In Ruby, the initialize method is a special method called automatically when you create a new object from a class. It sets up the initial state or values for that object, like giving it its starting properties.
⚙️

How It Works

Think of the initialize method as the setup step when you buy a new gadget. Just like you might charge it or install batteries before using it, Ruby calls initialize to prepare a new object with the right starting values.

When you write ClassName.new, Ruby creates a fresh object and then runs the initialize method inside that class automatically. This method can take inputs (called parameters) to customize the object’s properties right away.

💻

Example

This example shows a simple class with an initialize method that sets a name for a person when you create a new instance.

ruby
class Person
  def initialize(name)
    @name = name
  end

  def greet
    "Hello, my name is #{@name}!"
  end
end

person = Person.new("Alice")
puts person.greet
Output
Hello, my name is Alice!
🎯

When to Use

Use the initialize method whenever you want to set up an object with specific starting information. For example, if you create a class for a car, you might want to set its color and model right when you make a new car object.

This helps keep your code organized and makes sure every object starts with the right data, avoiding mistakes later.

Key Points

  • initialize runs automatically when creating a new object.
  • It sets up initial values for the object’s properties.
  • You can pass arguments to initialize to customize each object.
  • It helps keep your objects ready to use right after creation.

Key Takeaways

The initialize method sets up new objects automatically when created.
It allows passing values to customize each object’s starting state.
Using initialize keeps your code clean and objects ready to use.
Every Ruby class can have one initialize method to prepare new instances.