Explain it simply
Explain it simply
initialize is the method Ruby calls automatically right after Car.new creates a blank object. Its job is to give the new object the data it needs before anyone else touches it. It works like filling in a form when you open a bank account: the account is never allowed to exist half-filled.
You never call initialize yourself. You describe what a new object needs through initialize's parameters, and every Car.new(...) call passes its arguments straight to it. That way a Car without a brand simply cannot be created, and the mistake is reported on the line that caused it.
Problem → Why → Solution
The problem: half-built objects
In the previous lesson you built objects by calling Car.new and then filling in data with setters. Nothing forces the caller to set everything, so an object can exist half-built. In the code below the color is never set, the description method assumes it exists, and the failure appears far from the place that forgot it.
class Car
attr_accessor :brand, :color
def description
"#{color.upcase} #{brand}"
end
end
car = Car.new
car.brand = "Toyota" # the color was never set
puts car.description
# NoMethodError: undefined method 'upcase' for nilWhat initialize guarantees
When an object can exist half-built, every method has to guess which fields are present. initialize turns 'a Car always has a brand and a color' into a rule Ruby enforces: Car.new with missing arguments fails immediately, on the line that is wrong, instead of later in some unrelated method.
Core concept: new builds, initialize fills
initialize is an ordinary instance method with a special role. Car.new allocates a blank object, calls initialize on it with the arguments you passed to new, and then returns the object. You never call initialize yourself; it is private, so car.initialize raises NoMethodError: private method 'initialize' called for an instance of Car. Whatever initialize returns is ignored, and new always returns the new object.
Because the arguments travel through new, Ruby checks them like any method call. Calling Car.new("Toyota") on a two-parameter initialize raises ArgumentError: wrong number of arguments (given 1, expected 2). With keyword arguments, a missing one gives missing keyword: :color and an unknown one gives unknown keyword: :colour. These errors are a gift, because they stop a half-built object at birth.
Parameters can have defaults (def initialize(brand, color = "white")) or be keywords (brand:, color: "white"). Keywords read better once there are more than two or three values: Car.new(brand: "Toyota", color: "Red") says what each value means, and the order no longer matters. A good rule is positional for one or two obvious values and keywords beyond that.
initialize is also the place to validate and normalise: reject nonsense with raise ArgumentError, "...", strip text and apply defaults, so every other method can trust the data. Set all instance variables here, even when the starting value is nil or an empty array, so a reader sees the full list of an object's fields in one place and typos stand out. Remember that a mistyped variable inside another method, @colour instead of @color, does not fail; it quietly reads nil.
For classes that are nothing but a bundle of fields, Ruby offers shortcuts that write initialize for you. Struct.new(:brand, :color) builds a class with accessors, ==, to_s, inspect and positional initialization. Data.define(:brand, :color), available since Ruby 3.2, builds an immutable version: it has no setters, its instances are frozen, and you use with(color: "Blue") to make a modified copy. Both accept keyword arguments too, and Data insists on exactly the right ones.
- Car.new allocates an empty object
- Ruby calls initialize with your arguments
- initialize assigns the @variables
- new returns the finished object
If the arguments are wrong, ArgumentError appears before initialize's body runs, so nobody ever sees a half-built object.
General pattern
class ClassName
def initialize(required, optional = default, keyword:, other: default)
@required = required
@optional = optional
@keyword = keyword
end
end
ClassName.new(value, keyword: value)The parameter list can mix positional, defaulted and keyword (keyword:) parameters. In the body each parameter is assigned to an instance variable starting with @, so the value outlives the method. The arguments of ClassName.new(...) go straight to initialize.
Example: a Car created with a brand and a color
This Car class uses initialize to store the brand and color at the moment the object is built. The description method reads those instance variables and builds one line of text. Unlike the setter approach of the previous lesson, the object that comes out of Car.new already has all its data.
brand is a parameter, while @brand is the instance variable stored inside the object. Keep them apart: the parameter disappears when initialize ends, but @brand stays for as long as the object lives.
class Car
def initialize(brand, color)
@brand = brand
@color = color
end
def description
"#{@color} #{@brand}"
end
end
toyota = Car.new("Toyota", "Red")
puts toyota.descriptionCode breakdown
- initialize
def initialize(brand, color)This method receives the two arguments given to new. brand and color are plain local variables that vanish when initialize ends, so the next lines copy them into the object.
- assign
@brand = brandThe left @brand is the object's instance variable and the right brand is the parameter. Without this assignment @brand would stay nil and description would show a blank.
- read
"#{@color} #{@brand}"Other methods read the instance variables. Color is written before brand, which gives Red Toyota; swap them and you would get Toyota Red.
- new
toyota = Car.new("Toyota", "Red")The arguments are positional: the first is brand and the second is color. new allocates the object, calls initialize("Toyota", "Red") and hands the finished Car to toyota.
- output
puts toyota.descriptiondescription joins @color and @brand and returns the string, so the output is Red Toyota. Passing only one argument, as in Car.new("Toyota"), would raise ArgumentError before description is ever reached.
Red ToyotaDefaults, keyword arguments and ArgumentError messages
The first snippet gives a positional parameter a default and shows the error you get for a wrong argument count; "expected 1..2" is the range of counts it accepts. The second snippet uses keywords: brand: has no default so it is required, while color and doors have defaults. The error messages below were copied from a run on Ruby 4.0.9, and the wording can differ slightly between versions.
class Bike
def initialize(brand, color = "white")
@brand = brand
@color = color
end
end
begin
Bike.new
rescue ArgumentError => e
puts "ArgumentError: #{e.message}"
# wrong number of arguments (given 0, expected 1..2)
endclass Truck
def initialize(brand:, color: "white", doors: 4)
@brand = brand
@color = color
@doors = doors
end
def to_s
"#{@color} #{@brand} (#{@doors} doors)"
end
end
puts Truck.new(brand: "Toyota") # white Toyota (4 doors)
puts Truck.new(brand: "Honda", color: "blue", doors: 2) # blue Honda (2 doors)
attempts = [
-> { Truck.new }, # missing keyword: :brand
-> { Truck.new("Toyota") }, # given 1, expected 0
-> { Truck.new(brand: "Toyota", colour: "red") }, # unknown keyword: :colour
]
attempts.each do |attempt|
attempt.call
rescue ArgumentError => e
puts "ArgumentError: #{e.message}"
endThe three errors from the second snippet read missing keyword: :brand, wrong number of arguments (given 1, expected 0; required keyword: brand) and unknown keyword: :colour. The last one catches a misspelling like colour immediately, which is one reason keywords beat positional parameters. The lambdas (-> { ... }) and rescue appear here only as tools; later lessons explain them properly.
Validating inside initialize
Think of initialize as the front door of an object. If you check there, an Account can never be created with bad data, so every other method can trust that the balance is not negative. Read raise ArgumentError, "..." as 'stop right here and report a problem'; the Exceptions lesson explains raise and rescue fully. Also notice that owner.strip normalises the input. At the end the code shows that calling initialize yourself fails because it is private.
class Account
attr_reader :owner, :balance
def initialize(owner, balance = 0)
raise ArgumentError, "owner can't be blank" if owner.to_s.strip.empty?
raise ArgumentError, "balance can't be negative: #{balance}" if balance.negative?
@owner = owner.strip
@balance = balance
end
end
acct = Account.new(" Aye ", 500)
puts "#{acct.owner}: #{acct.balance}" # Aye: 500
[["", 10], ["Bo", -5]].each do |owner, balance|
Account.new(owner, balance)
rescue ArgumentError => e
puts "Rejected: #{e.message}" # owner can't be blank / ...negative: -5
end
begin
acct.initialize("X")
rescue NoMethodError => e
puts e.message # private method 'initialize' called for an instance...
endStruct and Data.define: initialize written for you
| Struct | Data.define | |
|---|---|---|
| Setters | Yes (p1.x = 10) | No, instances are immutable |
| Missing argument | Filled with nil | ArgumentError (missing keyword) |
| Modified copy | dup it, then change it | with(lat: 17.0) |
| Use it for | A bag of fields that may change | A value-like record that never changes |
Check these differences yourself below. The inspect forms shown are what Ruby 4.0.9 printed: #<struct Point x=10, y=2> for Struct and #<data Coord lat=16.8, lng=96.2> for Data. Data.new accepts positional (Coord.new(16.8, 96.2)) as well as keyword arguments, but an incomplete set raises a missing keyword error.
Point = Struct.new(:x, :y)
p1 = Point.new(1, 2)
p1.x = 10
p p1 # #<struct Point x=10, y=2>
puts p1 == Point.new(10, 2) # true
p Point.new(1) # #<struct Point x=1, y=nil>
Coord = Data.define(:lat, :lng)
c1 = Coord.new(lat: 16.8, lng: 96.2)
p c1 # #<data Coord lat=16.8, lng=96.2>
p c1.with(lat: 17.0) # #<data Coord lat=17.0, lng=96.2>
puts c1.frozen? # true
begin
c1.lat = 1
rescue NoMethodError => e
puts e.message # undefined method 'lat=' for an instance of Coord
end
begin
Coord.new(lat: 1)
rescue ArgumentError => e
puts e.message # missing keyword: :lng
endIn real projects
Where this shows up in real projects
In real Ruby projects initialize is how dependencies and settings enter an object. A service such as PaymentService.new(order, gateway) receives everything it needs through initialize, and a test can pass in a fake gateway instead of the real one. Configuration objects, form objects and API clients follow the same pattern. In Rails you rarely write initialize for models, because ActiveRecord supplies one that accepts a hash of attributes (User.new(name: "Aye")), but you write it constantly for the plain Ruby objects around them.
Keep initialize cheap: assign, validate, set defaults and stop. Opening a network connection or reading a file inside initialize makes objects slow to create and awkward to test, so do that work in a separate method such as connect or load, or lazily on first use. For small immutable records such as coordinates, money amounts or API responses, Data.define gives you a correct initialize, equality and a readable inspect without writing any of them.
Common mistakes
Common mistakes
1. Passing positional arguments in the wrong order
Writing Car.new("Red", "Toyota") raises no error, and description returns Toyota Red, because both are strings and nothing can check them. When two parameters have the same type and are easy to confuse, use keywords (brand:, color:); the call site then explains itself, and a wrong keyword raises ArgumentError.
2. Mistyping an instance variable name
If initialize sets @color and another method reads @colour, Ruby raises no error; it returns nil and prints "color=" with nothing after it, because an unset instance variable reads as nil. Set every instance variable in initialize and read them through attr_reader, so that a misspelled method name raises NoMethodError instead.
3. Forgetting to store the parameter
With def initialize(brand); end and no @brand = brand, the parameter vanishes when initialize ends and @brand stays nil. Writing brand = brand is also wrong: it assigns a local variable to itself, so nothing reaches the object. In review, check that every parameter has a matching @name = name.
4. Doing heavy work in initialize
Putting a database connection, a file read or a network call in initialize makes them run on every single object and makes tests hard to isolate, and when one fails Car.new itself fails. Limit initialize to assigning, validating and setting defaults, and keep the rest in separate methods.
Best practices
Best practices
- Use positional parameters for one or two obvious values and keyword arguments beyond that.
- Set every instance variable in initialize, even when it starts as nil, so the object's fields are listed in one place.
- Keep initialize light and reject invalid input immediately with raise ArgumentError.
- For small records that never change, prefer Data.define over writing initialize by hand.
Mini challenge
Mini challenge: a Ticket that validates itself
Write a Ticket class for a concert. It is built with keyword arguments and must reject invalid values inside initialize. Finish with a small seat record made with Data.define.
- Write Ticket#initialize(event:, price:, seats: 1); raise ArgumentError "price must be positive, got -5" for a non-positive price and "seats must be between 1 and 6, got 9" for seats outside 1..6
- total returns price * seats and to_s returns text like "Concert x2 = 3000 yen"
- Print one valid Ticket, then rescue three invalid attempts (negative price, seats 9, missing event) and print "Rejected: <message>" for each
- Create Seat = Data.define(:row, :number), then print a seat and a with copy that changes the number, using inspect
class Ticket
# TODO: initialize(event:, price:, seats: 1)
# raise ArgumentError for a bad price or a bad seat count
# TODO: total and to_s
end
# TODO: print one valid ticket (Concert, price 1500, 2 seats)
# TODO: three bad attempts in an array of lambdas, each rescued and printed as
# "Rejected: <message>"
# TODO: Seat = Data.define(...), a seat, and a copy made with with(...)Expected: Concert x2 = 3000 yen Rejected: price must be positive, got -5 Rejected: seats must be between 1 and 6, got 9 Rejected: missing keyword: :event #<data Seat row="B", number=7> #<data Seat row="B", number=8>
Show hint
(1..6).cover?(seats) tests whether seats falls inside the range. You do not write the error for a missing event: a keyword parameter without a default makes Ruby raise missing keyword: :event by itself. Use puts seat.inspect to print the Data object.
Show solution
class Ticket
def initialize(event:, price:, seats: 1)
unless price.positive?
raise ArgumentError, "price must be positive, got #{price}"
end
unless (1..6).cover?(seats)
raise ArgumentError, "seats must be between 1 and 6, got #{seats}"
end
@event = event
@price = price
@seats = seats
end
def total
@price * @seats
end
def to_s
"#{@event} x#{@seats} = #{total} yen"
end
end
puts Ticket.new(event: "Concert", price: 1500, seats: 2)
attempts = [
-> { Ticket.new(event: "Concert", price: -5) },
-> { Ticket.new(event: "Concert", price: 1500, seats: 9) },
-> { Ticket.new(price: 1000) },
]
attempts.each do |attempt|
attempt.call
rescue ArgumentError => e
puts "Rejected: #{e.message}"
end
Seat = Data.define(:row, :number)
seat = Seat.new(row: "B", number: 7)
puts seat.inspect
puts seat.with(number: 8).inspectQuick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Car.new allocates an object, calls initialize with the arguments and returns the new object; initialize's return value is ignored and initialize is private.
- Positional, default and keyword parameters all raise ArgumentError for bad arguments (wrong number of arguments, missing keyword, unknown keyword).
- Set every instance variable in initialize and validate with raise ArgumentError; keep it light and leave network or file work out of it.
- Struct fits a changeable bag of fields and Data.define fits an immutable record; both write initialize for you.
Official Ruby Documentation — Ruby Documentation