Initialize method in ruby class

Ed Ancerys
2 min readApr 11, 2020

--

Initialize method is a “special” method in Ruby class that automatically gets called when we create a new instance of the class. It will help us to create new class objects way easier, and with fewer lines of code.

Initialize method in ruby

Creating class in Ruby

Imagine the scenario where we have a class called “Car” that takes in three parameters make, model, and color. To create this class in ruby with getters and setters let us explore the following example:

class Car

attractive_accessor :make, :model, :colour
end

To create a new object of the class “Car” and assign those values as per above example we need to do the following:

car_1 = Car.new()
car_1.make = "Ford"
car_1.model = "Model T"
car_1.colour = "Black"

Analyzing the code above, we can see that just to create one object we had to write four lines of code. And if that does not sound like a big deal now it might be a problem after a while… Imagine a scenario where we want to create 10, 20, or even 100 of these “car” objects?

Introducing to Initialize method in Ruby

And that’s where initialize methods come in handy. It is a special method in a way as it always gets called when a new instance of the class gets created.

So let us dig in a bit deeper and see how we can create this method and help us to refactor and optimize our code. All we need to do is to define a method… you guessed it… called “initialize” and assign values passed in by the user.

class Car

attractive_accessor :make, :model, :colour
def initialize(make, model, colour)
@make = make
@model = model
@colour = colour
end
end

So now whenever we want to create a new object of the class “Car” all we need to do is adding a line of code:

car_1 = Car.new("Ford", "Model T", "Black")

And that’s all it takes to create a new object of the class “Car” with the help of the “initialize” method. As previously, we needed to pass in and assign all values line by line, where now it all can be done in one line of code. We not only manage to make it more readable but reduced our code significantly.

And that is all! That is how we can use the “initialize” method in classes folks!

Conclusions

Whenever Ruby creates a new object, it looks for a method named “Initialize” and calls it. We can assign default values into instance variables that can be accessed anywhere in a class. The bottom line “Initialize” method helps to write cleaner, more readable code with fewer lines of code.

--

--