How to Use The Initialize Method in Ruby

The initialize method is part of the object-creation process in Ruby & it allows you to set the initial values for an object.

In other programming languages they call this a “constructor”.

For example:

Let’s say that you have a Point class, this point needs two coordinates, x & y.

How are you going to pass these values into the object?

Like this:

Point.new(10, 20)

The new method is how you create new objects in Ruby from a class like Point, or any other class that you have access to.

The Relationship Between New & Initialize

Notice these two arguments, 10 & 20?

Here’s where we come back to the initialize method.

If you try to pass arguments into new & if you don’t define initialize you’re going to get an error:

ArgumentError: wrong number of arguments (2 for 0)

Because when you call new, Ruby calls initialize!

You need this:

class Point
  def initialize(x, y)
  end
end

Now you can create Point objects with two arguments.

So the whole point of initialize is to allow you to create objects with arguments.

Saving The Arguments

Arguments passed into initialize aren’t automatically saved anywhere.

You have to do this using instance variables:

class Point
  def initialize(x, y)
    @x = x
    @y = y
  end
end

This will assign the values of x & y to the instance variables (@x & @y) so you can access them later.

A few points to note about initialize:

  • You can define optional & default arguments
  • Using return inside this method doesn’t make sense because it is special & it’ll ALWAYS return a new object
  • Defining initialize is NOT necessary if your class doesn’t require arguments

You can call other methods inside initialize, but you don’t want to do any real work here beyond what’s necessary to prepare the object to be used.

For example:

If your class is all about working with the Github API, you wouldn’t want to pre-load all possible requests to the API before hand.

You just want to save the API key into an instance variable.

Or whatever data your class needs.

Initializing Hashes & Other Built-In Objects

Built-in objects like hashes have special ways to initialize & create them besides calling new.

Ways to create a hash:

h = Hash.new
h = Hash['a', 1]
h = {}

Ways to create a string:

s = String.new
s = ""
s = %Q()

Ways to create an array:

a = Array.new(5)
a = %w(a b c)
a = []

The %w creates an array of strings.

Summary

You’ve learned about the Ruby initialize method, how it’s related to the new method, and the basics of object creation in Ruby.

Keep learning by reading this intro to Object-Oriented Programming in Ruby.

Thanks for reading!