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.
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.
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.