Polymorphism is a principle of
object-oriented programming that allows objects of one class to use methods of another class. This can be achieved through special mechanisms such as method overriding or interfaces.
In Ruby, polymorphism can be created by using a common method name for different classes.
Example of Using Polymorphism in Ruby
# Creating a Shape class with a draw method
class Shape
def draw
raise NotImplementedError, 'Subclasses must implement the draw method'
end
end
# Creating a Circle class that inherits from Shape
class Circle < Shape
def draw
puts 'Drawing a circle'
end
end
# Creating a Rectangle class that also inherits from Shape
class Rectangle < Shape
def draw
puts 'Drawing a rectangle'
end
end
# Using polymorphism
circle = Circle.new
rectangle = Rectangle.new
# Calling the draw method for the circle
circle.draw
# Calling the draw method for the rectangle
rectangle.draw
In this example, both classes
Circle and
Rectangle inherit from the base class
Shape and implement the
draw method. When the
draw method is called for objects of the
Circle and
Rectangle classes, the corresponding implementations of the method are invoked, which expresses polymorphism. It will also be useful to read about
inheritance in ruby.