Lesson 3
Exploring Polymorphism in Ruby OOP
Introduction

Greetings! In today's lesson, we'll delve into the concept of polymorphism in Ruby's Object-Oriented Programming (OOP). Understanding polymorphism empowers us to use a single entity (a method, class, or module) to represent different behaviors in various scenarios. Let's proceed.

Polymorphism: A Powerful OOP Principle

Polymorphism, a fundamental principle of OOP, allows one object to appear in multiple forms. Imagine a button in software; depending on its type (for example, a submit button or a radio button), the action resulting from pressing it can differ. This flexibility embodies the essence of polymorphism!

Seeing Polymorphism in Action

Let's explore polymorphism through a simple application involving shapes. The base Shape class will have an area method, which calculates the area for shapes. This method will be uniquely implemented in the subclasses Rectangle and Circle.

Ruby
1class Shape 2 def area 3 raise 'NotImplementedError' 4 end 5end 6 7class Rectangle < Shape 8 def initialize(length, width) 9 @length = length 10 @width = width 11 end 12 13 def area 14 @length * @width 15 end 16end 17 18class Circle < Shape 19 def initialize(radius) 20 @radius = radius 21 end 22 23 def area 24 3.14 * @radius * @radius 25 end 26end 27 28shapes = [Rectangle.new(2, 3), Circle.new(5)] 29shapes.each do |shape| 30 puts shape.area 31end 32# Output: 6 33# Output: 78.5

Here, polymorphism shines as the area method adopts multiple forms and behaves differently depending on whether it's part of a Rectangle or a Circle.

When and Why to Use Polymorphism

Polymorphism is invaluable when working with inheritance, as a single action can exhibit different behaviors for different object types, streamlining the code while enhancing readability and maintainability.

Lesson Summary and Practice

Great job! We've now learned about polymorphism, observed its implementation, and discovered its applications within Ruby. Prepare for hands-on practice tasks, apply what you've learned, and excel in Ruby programming. Happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.