All original content is created in Ukrainian. Not all content has been translated yet. Some posts may only be available in Ukrainian.Learn more

What is polymorphism? An example of using polymorphism in Ruby.

Table of contentsClick link to navigate to the desired location
This content has been automatically translated from Ukrainian.
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.

This post doesn't have any additions from the author yet.

29 Nov 08:47

What is the difference between var and let in Javascript?

meme code
meme code@memecode
07 Dec 07:42

What is encapsulation in OOP?

meme code
meme code@memecode
07 Dec 08:13

Visibility control in Ruby (public, private, and protected)

meme code
meme code@memecode
07 Dec 08:25

What is OOP (object-oriented programming)?

meme code
meme code@memecode
09 Dec 12:00

What is inheritance in Ruby? Examples of bad and good inheritance.

meme code
meme code@memecode
09 Dec 12:15

What is best practice in programming?

meme code
meme code@memecode
09 Dec 12:46

Що таке патерн/шаблон проєктування?

meme code
meme code@memecode
10 Dec 14:03

What is a design pattern in programming?

meme code
meme code@memecode
10 Dec 14:18

What is a client and a server? What is the interaction mechanism between the client and the server?

meme code
meme code@memecode
18 Dec 08:25

What is DNS? What is DNS used for?

meme code
meme code@memecode
18 Dec 08:44

What is a domain (domain name)?

meme code
meme code@memecode
19 Dec 18:15

What are SSL and TLS? What is the difference?

meme code
meme code@memecode