Thuta Learning
AdvancedProgrammingbeginner

Initialize Method

Relax. We'll talk through this in plain words — no textbook voice.

initialize method is a constructor that runs automatically when a new object is built. It's used to set up whatever data an object needs right when it's created.

ruby
class Car
  def initialize(brand, color)
    @brand = brand
    @color = color
  end

  def description
    "#{@color} #{@brand}"
  end
end

toyota = Car.new("Toyota", "Red")
puts toyota.description

Car.new("Toyota", "Red") is called, initialize runs. @brand and @color are instance variables stored inside the object.

You should see
Red Toyota

Info

Instance variables can be reused across multiple methods. A local variable, on the other hand, only exists within a single method.

Easy traps

  • If initialize expects two arguments and you only pass one, like Car.new("Toyota"), you'll get an ArgumentError.