Instantiating and Initializing An Object in Ruby

Laina Karosic
3 min readMar 16, 2020

--

When we create a new class in Ruby, we’re building a template of instructions. But without ever instantiating any actual objects from within this class, that’s all that will remain — just instructions!

So how do we actually use these instructions to make something? We instantiate the object.

Instantiating an object in Ruby relies on a class as a template and, upon the actual instantiating, actually brings the object to life. So first, let’s make a Coffee class.

class Coffeeend 

Next, let’s create a new instance of this Coffee class. We can use Ruby’s built-in .new method. We can set it equal to a variable ‘colombian’ so it’s easier to access later.

class Coffeeendcolumbian = Coffee.new

Voila! We just instantiated this first instance of Coffee! The last line of code we just added will return the following:

class Coffeeendcolumbian = Coffee.new # => <Coffee:0x00007fe83f991888>

That last line there is one actual instance of the coffee class. It’s the Coffee object. Now that it has been instantiated, it exists in memory (you can test it out in irb).

Let’s create more attributes for our brand new coffee object.

Note that when you call colombian.type the first time, it returns nil because you haven’t passed any arguments into the type= method. So it hasn’t set type equal to anything yet! Type is still equal to nil. Once you pass in a string of whatever coffee type you want (we used “colombian”), then it sets type equal to that string. Now, when you call colombian.type again, it will return “colombian” just like we want it to!

Now, let’s say we want our coffee to be given a type right when we create Coffee.new, instead of going through all of these steps each time. Is there a way Ruby can streamline this for us?

YES!

This is called initialization. When we first create that brand new instance of our our Coffee class, we can use a special Ruby method #initialize to give it this power:

Aha! And if you look closely at what our Coffee.new returns after passing it an argument at the same time we’re creating it, you’ll see it returns not only the coffee object, but it now has a @type attribute already, as soon as it was created! The initialize method made that possible.

The magic of the initialize method works like this: When .new is called, it automatically invokes (runs) the initialize method. It also passes any arguments from the .new method to the initialize method. In this case, we used that argument (“colombian”) to give our type attribute a value. You can initialize and pass in more than one argument at a time, but this is a basic example to help solidify the fundamentals and help distinguish between instantiating —creating an instance of an object, and initializing — assigning attributes to that object as soon as it’s created.

--

--