The Initialize Method

Aidan McBride
Using the Initialize Method In Ruby
6 min readMar 31, 2020

One of the best parts of learning to program in Ruby is that it is an Object-Oriented language. This means that everything in Ruby is an object, from strings to hashes to my favorite, classes. Classes in Ruby are a fantastic way to create objects; they act as a blueprint and allow for flexibility. And nothing makes a class more useful then defining an initialize method within it.

When I first heard of an initialize method, this is what I thought of

Let’s say you are creating your first web application. You have a great idea to create an application that allows users to order tomato seeds online! No more waiting around at the farmer’s market for you, you can get an early start on this growing season. Inside your application, you want to define your class “TomatoSeed” so that you can create an object to be added to your user’s shopping cart. This will look something like this:

This is a great start. Now you can create each instance of a TomatoSeed using this blueprint. Using the new() method, you can create an instance, like Ramapo, of your TomatoSeed class:

And thus an object called ramapo now exists as a TomatoSeed class. But this does not give us much information at all about this particular type of tomato. After all, tomatoes have lots of important information about them we are going to want to know if we are going to plant them.

Bob the tomato wonders why you don’t ask about his disease resistance

Enter the initialize method.

If we want to create a new instance of TomatoSeed, we can define an initialize method inside the TomatoSeed class that automatically assigns arguments as instance variables. Instance variables are variables that will be unique to each instance of a class. When instance variables are put in an initialize statement, it ensures that every time a new instance of that class is created, it has those variables attached. Let’s see an example with TomatoSeeds. What are some common things about our tomato plant that we would want to know when purchasing seeds?

With this initialize method, the new TomatoSeed object will be created with instance variables equal to the values defined in the initialize statement’s parameters. In other words, when we create a new instance of TomatoSeeds, we will pass it arguments for the number of days it takes a tomato to mature, whether it is disease resistant or not, and its size when fully mature.

What does that look like?

Now we have a ramapo tomato seed that lets us know what to expect from it. More importantly, we have a class with instance variables defined by arguments! (In case you were wondering, Ramapo tomatoes are also resistant to verticillium wilt, so they are a must-have for your summer garden.)

The most important part about this initialize method is that it is running every time we create a new instance of TomatoSeeds, automatically. This ensures that all TomatoSeed instances have the same attributes. Another fantastic feature of the initialize method is its ability to work with class variables.

The @@all Class Variable

In our seed buying application were going to need a list of all the available TomatoSeed instances for the user to choose from. We can add each new instance of a class to an array using our initialize method! By creating a class variable with the double @ sign(@@), we can push an instance of the class called self into an array. In the following code, an empty array is defined and attached to the class TomatoSeed. Inside the initialize method, an instance of TomatoSeed is added to this array. Every time a new instance is created, the initialize method runs, and that instance of TomatoSeed is added to the array.

It quickly becomes apparent how the initialize method is a necessity when working with classes in Ruby. However, this is one slight problem we could face given our current code. What if we have to add an instance of tomato to our catalog but we aren’t sure if it is disease resistant? Or even more likely, what if we forget which order our arguments go when creating our new instance of tomato seed?

Using a Hash as an Argument

Luckily, Ruby’s initialize method has a solution for this too. By passing a hash containing key value pairs into the initialize statement, we no longer have to consider the order of arguments. For example, by setting up our initialize statement like this :

We can accept a single argument, a hash, that looks like any one of the following:

In the early-girl tomato options hash, we have mixed the order of the key-value pairs. This is no problem, however, because initialize reads the hash it is passed all at once and can search for the appropriate key and value to match its instance variable. Notice in the last hash, we are missing the disease-resistant value of true or false. Since no such key value is present in the hash, if we call desease_resistant on the new instance of TomatoSeed it will simply return nil instead of throwing an error. No more given vs expected argument errors!

No more frustrating argument errors

In addition to taking a hash as an argument, an initialize method can also set a parameter to a default value. This can be done by setting the parameter equal to a value inside in the parameter rather than in the definition. For example, if we wanted to declare that all tomatoes like sandy loam soil, we could write:

Tomatoes can grow in almost any soil besides clay, but they love sandy loam soil. This is why the tomatoes in New Jersey are so delicious.

This will set the default value to soil preference to sandy loam soil. However, if we want to change this for a specific instance of a tomato, we can implicitly declare that as an argument when we create the new instance.

Once I grasped these concepts about the Ruby initialize method, working with object-oriented programing became vastly easier and much more exciting. I hope this information has been insightful and can help you write better and more versatile code.

--

--

Aidan McBride
Using the Initialize Method In Ruby

I am a Front End Engineer and graduate of Flat Iron coding bootcamp. Currently I work in the regulatory industry using React.