Initializing Objects

Learn how we initialize objects in Ruby.

We'll cover the following

Let’s start over and define a new class.

Remember that objects can be thought of as two things. They know stuff, and they can do things.

Let’s define a Person class. People obviously also know things and can do things.

Here’s how to define a new empty Person class:

class Person
end

Again, that’s not a very useful class, but we can instantiate it and create an actual, concrete person instance (object) from it:

Press + to interact
class Person
end
Person.new

The initialize method

Now, before we add any behavior (methods) to our class, we want to be able to give it some initial data. In our case, we want the person to know its own name.

We can do this like so:

Press + to interact
class Person
def initialize(name)
end
end

Notice that we add a method called initialize to the class. This method accepts a single argument called name. At the moment, this method is still empty. We’ll add some code to it in a bit.

It’s important to know that the initialize method has a special meaning in Ruby: Whenever we call the new method on a class, as in Person.new, the class creates a new instance of itself. It then calls the initialize method on the new object. This simply passes all arguments we passed to new on to the initialize method.

So, we can now create a new person instance by calling the following:

Press + to interact
Person.new("Ada")

The "Ada" string passes on to our initialize method and is assigned to the local name variable.

Remember: The special initialize method is called internally when the object has been created by the new class method.

Our initialize method doesn’t do anything with the string passed yet. More on that in the next lesson.

To recap, when we call new on the Person class and pass the "Ada" string, the new method creates a new instance of the class and calls initialize on it, passing the same argument list, which in our case is the single "Ada" string.