0
0
Rubyprogramming~5 mins

Why modules solve multiple inheritance in Ruby

Choose your learning style9 modes available
Introduction

Modules let you share code between classes without the problems of multiple inheritance. They help keep code simple and organized.

You want to add the same behavior to different classes without repeating code.
You need to share methods but your classes already have a parent class.
You want to avoid confusion from inheriting from more than one class.
You want to keep your code easy to understand and maintain.
You want to add features to classes without changing their inheritance.
Syntax
Ruby
module ModuleName
  def method_name
    # code here
  end
end

class ClassName
  include ModuleName
end

Use module to group methods that can be shared.

Use include inside a class to add module methods as instance methods.

Examples
This example shows a module Talkative with a method talk. The class Dog includes it to get the talk method.
Ruby
module Talkative
  def talk
    puts "Hello!"
  end
end

class Dog
  include Talkative
end

d = Dog.new
d.talk
Both Fish and Human classes include the Swimmer module to share the swim method without inheritance.
Ruby
module Swimmer
  def swim
    puts "Swimming!"
  end
end

class Fish
  include Swimmer
end

class Human
  include Swimmer
end
Sample Program

This program shows a Duck class that includes two modules: Flyer and Swimmer. The duck can both fly and swim without inheriting from multiple classes.

Ruby
module Flyer
  def fly
    puts "I can fly!"
  end
end

module Swimmer
  def swim
    puts "I can swim!"
  end
end

class Duck
  include Flyer
  include Swimmer
end

d = Duck.new
d.fly
d.swim
OutputSuccess
Important Notes

Ruby does not allow a class to inherit from more than one class, but modules let you add many behaviors.

Modules help avoid conflicts and keep your code clean.

Summary

Modules let you share code without multiple inheritance problems.

You include modules in classes to add methods easily.

This keeps your code simple, reusable, and easy to understand.