Ruby's multiple inheritance

Ruby does not support traditional multiple inheritance, where a class can inherit directly from multiple parent classes. Instead, Ruby employs a feature called mixins, which allows classes to incorporate behavior from multiple modules. Mixins provide a way to reuse and share code across different classes without introducing the complexities and potential conflicts of multiple inheritance.

A mixin is a module that defines a set of methods and behaviors which can be included in other classes. The include keyword is used to include a module within a class, making the module's methods and behaviors available to instances of that class. Let's see an example:

module Flyable
  def fly
    puts 'Flying!'
  end
end

module Swimmable
  def swim
    puts 'Swimming!'
  end
end

class Bird
  include Flyable
end

class Duck < Bird
  include Swimmable
end

duck = Duck.new
duck.fly    # Output: Flying!
duck.swim   # Output: Swimming!

In this example, we define two modules: Flyable and Swimmable, each containing specific behaviors. The Bird class includes the Flyable module, allowing instances of Bird to have access to the fly method. The Duck class, which is a subclass of Bird, includes the Swimmable module, providing access to the swim method. As a result, instances of Duck can both fly and swim.

By using mixins, Ruby achieves a form of multiple inheritance by allowing classes to incorporate functionality from multiple modules. This approach promotes code reuse, modularity, and avoids the pitfalls associated with traditional multiple inheritance, such as the diamond problem.

One more example

module Walkable
  def walk
    puts "Walking..."
  end
end

module Swimmable
  def swim
    puts "Swimming..."
  end
end

class Animal
  include Walkable
end

class Fish
  include Swimmable
end

class Dolphin
  include Walkable
  include Swimmable
end

dog = Animal.new
dog.walk  # Output: Walking...

fish = Fish.new
fish.swim  # Output: Swimming...

dolphin = Dolphin.new
dolphin.walk  # Output: Walking...
dolphin.swim  # Output: Swimming...

"In this example, we define two modules: Walkable and Swimmable, each with their own set of methods. Then, we have three classes: Animal, Fish, and Dolphin."

"Animal includes the Walkable module, enabling instances of Animal to call the walk method."

"Fish includes the Swimmable module, allowing instances of Fish to call the swim method."

"Dolphin includes both the Walkable and Swimmable modules, so instances of Dolphin can call both the walk and swim methods."

"While this is not traditional multiple inheritance, it allows us to incorporate behavior from multiple modules into different classes, providing a form of 'multiple inheritance' in Ruby."

Last updated