0
0
Rubyprogramming~5 mins

Why single inheritance in Ruby

Choose your learning style9 modes available
Introduction

Ruby uses single inheritance to keep things simple and clear. It helps avoid confusion by allowing a class to inherit from only one parent class.

When you want to create a new class based on one existing class to reuse its behavior.
When you want to keep your code easy to understand and maintain.
When you want to avoid complex conflicts that can happen with multiple inheritance.
When you want to use Ruby's mixins (modules) to add extra features instead of multiple inheritance.
Syntax
Ruby
class ChildClass < ParentClass
  # child class code here
end
Ruby allows only one parent class after the < symbol, which means single inheritance.
To add more features, Ruby uses modules and mixins instead of multiple inheritance.
Examples
Dog inherits from Animal, so Dog can use the speak method and also has its own bark method.
Ruby
class Animal
  def speak
    puts "Hello"
  end
end

class Dog < Animal
  def bark
    puts "Woof!"
  end
end
Fish inherits from Animal and also includes the Swimmable module to add swimming behavior.
Ruby
module Swimmable
  def swim
    puts "Swimming"
  end
end

class Fish < Animal
  include Swimmable
end
Sample Program

This program shows a Car class inheriting from Vehicle. Car can use the start method from Vehicle and its own honk method.

Ruby
class Vehicle
  def start
    puts "Vehicle started"
  end
end

class Car < Vehicle
  def honk
    puts "Beep beep!"
  end
end

my_car = Car.new
my_car.start
my_car.honk
OutputSuccess
Important Notes

Single inheritance keeps the class hierarchy simple and easy to follow.

Ruby uses modules to add extra behavior without the problems of multiple inheritance.

Mixins (modules) are a flexible way to share code across classes.

Summary

Ruby uses single inheritance to keep code simple and clear.

Only one parent class is allowed, but modules can add extra features.

This design helps avoid conflicts and makes code easier to maintain.