Ruby - Call inherited method

Introduction

To call call an inherited method and do something with the result.

The following code defines some basic classes that represent different types of people:

class Person 
  def initialize(name) 
    @name = name 
  end 

  def name 
    return @name 
  end 
end 

class Doctor < Person 
  def name 
    "Dr. " + super 
  end 
end 

Here, you have a Person class that implements the basic functionality of storing and returning a person's name.

The Doctor class inherits from Person and overrides the name method.

Within the name method for doctors, it returns a string starting with Dr., appended with the name.

By using super, the code looks up the inheritance chain and calls the method of the same name on the next highest class.

Related Topic