Technology Encyclopedia Home >What are inheritance and polymorphism in Ruby?

What are inheritance and polymorphism in Ruby?

Inheritance and polymorphism are fundamental concepts in object-oriented programming, including Ruby.

Inheritance allows a class to inherit attributes and behaviors from another class. The class that inherits is called a subclass or derived class, and the class from which it inherits is called a superclass or base class. This promotes code reuse and establishes a natural hierarchy between classes.

Example: Suppose you have a superclass Animal with attributes like name and methods like eat. You can create subclasses like Dog and Cat that inherit these attributes and methods, and also add their own specific behaviors like bark for Dog and meow for Cat.

class Animal
  attr_accessor :name

  def eat
    puts "#{name} is eating."
  end
end

class Dog < Animal
  def bark
    puts "#{name} says woof!"
  end
end

class Cat < Animal
  def meow
    puts "#{name} says meow!"
  end
end

Polymorphism refers to the ability of different classes to be treated as instances of the same class through a common interface. It allows objects of different types to respond to the same method call, enabling flexibility and extensibility in your code.

Example: Continuing with the previous example, you can create an array of Animal objects that includes both Dog and Cat instances. When you call the eat method on each object, Ruby will execute the appropriate version of the method based on the actual object type.

animals = [Dog.new(name: "Buddy"), Cat.new(name: "Whiskers")]

animals.each do |animal|
  animal.eat
end

This will output:

Buddy is eating.
Whiskers is eating.

In the context of cloud computing, these concepts can be applied to design scalable and maintainable applications. For instance, you might use inheritance to create a base class for all cloud services and then derive specific service classes like ComputeService, StorageService, etc. Polymorphism can be used to handle different service requests uniformly, making your application more flexible and easier to extend.

If you're looking to deploy Ruby applications in the cloud, consider using services like Tencent Cloud's Cloud Functions or Container Service, which offer scalable and flexible environments for running your code.