← Back to Ruby Course | Chapter 9: OOP | Lesson 2 of 7

initialize

In this page:

  1. initialize

initialize

initialize is a special method that runs automatically whenever .new is called on a class, used to set up an object's initial state. Its parameters become the arguments you pass to .new. Unlike most methods, initialize is called implicitly and its return value is ignored -- .new always returns the new object itself.

Note: initialize's return value is always ignored -- .new always returns the newly created object, no matter what initialize returns.

Example: initialize

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

  def introduce
    puts "I'm #{@name}, #{@age} years old"
  end
end

alice = Person.new("Alice", 30)
alice.introduce
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.