Home »
Ruby Tutorial
Ruby Mixins
By IncludeHelp Last updated : December 03, 2024
Before reading this article on mixins, you should be very well aware of the things related to Object-Oriented programming and in that, particularly Inheritance.
Mixins
We all know that Ruby does not support multiple inheritances directly which means a child class cannot have more than one parent class. This simply means that it can only inherit the features of a single parent class. When we have to make a child class to inherit the features of more than one Base class, then we take help from Mixins. Mixins can also be considered as the mechanism to implement indirect multiple Inheritances. We use the method include to implement mixins and there is no restriction on the number of mixins a class may have. Let us understand mixins with the help of syntax and demonstrating program codes.
Syntax
class M1
Include M2
Include M3
end
Example 1
=begin
Program to demonstrate Mixins
=end
module Printhello
def prnt1
puts "Hello"
end
def prnt2
puts "Hi"
end
end
module Printbye
def prnt3
puts "Bye"
end
def prnt4
puts "Take Care"
end
end
class Includehelp
include Printhello
include Printbye
def Add
puts "Follow Includehelp on Instagram"
end
end
obj1 = Includehelp.new
obj1.prnt1
obj1.prnt2
obj1.prnt3
obj1.prnt4
obj1.Add
Output
Hello
Hi
Bye
Take Care
Follow Includehelp on Instagram
Explanation
In the above code, you can observe that we are implementing mixins as well as multiple inheritances in Ruby indirectly. The class Includehelp has two modules now, namely, Printhello and Printbye. The child class is now able to access all the methods or features of all the two base classes. This is how you can make a class multiply inherited in Ruby.
Example 2
=begin
Program to demonstrate Mixins
=end
module Parent_1
def a1
puts 'This is Parent one.'
end
end
module Parent_2
def a2
puts 'This is Parent two.'
end
end
module Parent_3
def a3
puts 'This is Parent three.'
end
end
class Child
include Parent_1
include Parent_2
include Parent_3
def display
puts 'Three modules have been included.'
end
end
object = Child.new
object.display
object.a1
object.a2
object.a3
Output
Three modules have been included.
This is Parent one.
This is Parent two.
This is Parent three.
Explanation
In the above code, you can observe that we are implementing mixins as well as multiple inheritances in Ruby indirectly. The class child has three modules now, namely, Parent_1, Parent_2, and Parent_3. The child class is now able to access all the methods or features of all the three base classes.