Ruby Inheritance and initialize Method Tutorial

  • Post author:
  • Post category:Ruby

In this section we will learn how to use initialize method in Ruby inheritance.

Note: we’re assuming you’re already familiar with the Ruby super keyword.

How does initialize method work in Ruby Inheritance?

In the Ruby initialized method section, we mentioned that the initialize method is a special method in Ruby classes that will be called when we create an object from the target class.

Also, we noted that it’s best to put instance variables into this method so that we get to initialize them right when the object is being created. That way, all the instance variables will be ready to use and there won’t be any error if a method accidentally tried to take the value of an instance variable.

Alright, now there’s one question remains and that is: what will happen if we create an initialize method in the body of a child class while the parent class also has one with instance variables in it? Which one of these initialize methods will be called if we try to create an object from the Child class?

Well, remember that we mentioned the initialize method is just another method in Ruby like other methods we’ve seen so far! So this means if both classes have the initialize method, that means the child class has overridden the same method of the parent class! So obviously it’s the child initialize method that will be called when an object is going to be created from the child class.

Now if the parent class has instance variables in the body of its initialize method, then we can use the `super` keyword in the child’s body initialize method and pass the required arguments to this keyword so that our program call the parent initialize method on the process of initialization and create those instance variables of the parent class as well.

Let’s see this in an example.

Example: using initialize method in Inheritance

class Person 
    attr_accessor :first_name, :last_name, :id 
    def initialize (first_name, last_name, id)
        self.first_name = first_name
        self.last_name = last_name 
        self.id = id 
    end 

end 

class Employee <Person 

    def initialize(first_name, last_name, id)
        super 
    end 
end 

emp = Employee.new("John","Doe",300)

puts emp.first_name, emp.last_name, emp.id 

Output:

John

Doe

300

As you can see, here we’ve called the initialize method of the Employee class, but then with the help of the `super` keyword, we’ve invoked the initialize method of the Person class as well, and create and initialized the instance variables that were in the parent class.

Leave a Reply