Open In App
Related Articles

Ruby Mixins

Improve Article
Save Article
Like Article

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
   def g2
# module consist 2 methods
module GFG
   def gfg1
   def gfg2
# Creating a class
class GeeksforGeeks
include G
include GFG
   def s1
# Creating object
gfg =
# Calling methods

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.'
module Child_2
  def a2
   puts 'This is Child two.'
module Child_3
  def a3
   puts 'This is Child three.'
# Creating class
class Parent
  include Child_1
  include Child_2
  include Child_3
  def display
   puts 'Three modules have included.'
# Creating object
object =
# Calling methods


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.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 21 Nov, 2019
Like Article
Save Article
Similar Reads
Complete Tutorials