Introduction to Polymorphism in Ruby
Introduction to Polymorphism
Welcome back! We're continuing our journey into object-oriented programming (OOP) with a new and exciting topic: Polymorphism. You've already learned about classes, objects, and inheritance, which are essential building blocks of OOP. Now, it's time to explore how polymorphism can make your code more flexible and reusable.
What You'll Learn
Polymorphism allows objects to be treated as instances of their parent class rather than their actual class. This provides a way to use a single interface to represent different types of objects. Here’s what we’ll cover in this lesson:
- Understanding Polymorphism: We'll discuss what polymorphism is and why it's a powerful concept in
Rubyprogramming. - Implementing Polymorphism in
Ruby: You'll learn how to use method overriding and duck typing to achieve polymorphism.
Understanding Polymorphism
Polymorphism in Ruby allows you to call methods of derived classes through a base class reference. This makes your code more dynamic and general. For example, consider the following Ruby code:
In this example, the display method of the derived classes (Student and Teacher) overrides the base class method in Person. When we call display on an instance of Student or Teacher, the Ruby interpreter automatically invokes the appropriate derived class method.
Let's also understand how Ruby resolves methods. Ruby uses a method lookup chain to resolve which method to invoke. When person1.display is called, Ruby first checks if the display method exists in the Student class. If found, it executes it. If not, it moves up to the Person class.
