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

initialize

initialize is the setup that runs automatically when you make a new object, like assembling and charging a toy as it leaves the box. It gives the object its first values.

In this page:

  1. initialize
Syntax
ruby
class ClassName
  def initialize(param1, param2)
    @attribute1 = param1
    @attribute2 = param2
  end
end

object = ClassName.new(value1, value2)

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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Naming it init or Initialize, when it must be exactly initialize.
  2. Calling Person.new with the wrong number of arguments, which raises ArgumentError.
  3. Forgetting the @ before instance variables, so the values are lost when the method ends.
🔒

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.