Before studying about Ruby Mixins, we should have the knowledge about Object Oriented Concepts. If we don’t, go through Object Oriented Concepts in Ruby . When a class can inherit features from more than one parent class, the class is supposed to have multiple inheritance. But Ruby does not support multiple inheritance directly and instead uses a facility called mixin. Mixins in Ruby allows modules to access instance methods of another one using include method.
Mixins provides a controlled way of adding functionality to classes. The code in the mixin starts to interact with code in the class. In Ruby, a code wrapped up in a module is called mixins that a class can include or extend. A class consist many mixins.
Below is the example of Ruby Mixins.
Example #1:
# Ruby program of mixins # module consist 2 methods module G
def g1
end
def g2
end
end # module consist 2 methods module GFG
def gfg1
end
def gfg2
end
end # Creating a class class GeeksforGeeks
include G
include GFG
def s1
end
end # Creating object gfg = GeeksforGeeks. new
# Calling methods gfg.g1 gfg.g2 gfg.gfg1 gfg.gfg2 gfg.s1 |
Here, module G consists of the methods g1 and g2. Module GFG consists of the methods gfg1 and gfg2. The class GeeksforGeeks includes both modules G and GFG. The class GeeksforGeeks can access all four methods, namely, g1, g2, gfg1, and gfg2. Therefore, we can see that the class GeeksforGeeks inherits from both the modules. Thus, we can say the class GeeksforGeeks shows mixin.
Consider the example below for elucidation.
Example #2:
# Modules consist a method module Child_1
def a1
puts 'This is Child one.'
end
end module Child_2
def a2
puts 'This is Child two.'
end
end module Child_3
def a3
puts 'This is Child three.'
end
end # Creating class class Parent
include Child_1
include Child_2
include Child_3
def display
puts 'Three modules have included.'
end
end # Creating object object = Parent. new
# Calling methods object.display object.a1 object.a2 object.a3 |
Output
Three modules have included. This is Child one. This is Child two. This is Child three.
In above example, module Child_1 consist of the method a1 similarly module Child_2 and Child_3 consist of the methods a2 and a3. The class Parent includes modules Child_1, Child_2 and Child_3 . The class Parent also include a method display. As we can see that the class Parent inherits from all three modules. the class Parent shows multiple inheritance or mixin.