Ruby Basics : Module

In this article you will learn about the concept of module and how to overcome single inheritance limitation.

Single Inheritance

In the previous article you learned that Ruby is a single inheritance language. We can have only one parent. In this article, we will see how Ruby overcomes this limitation by using module.

What is a Module?

Module provides a way to share behavior. We can define methods in the module and instead of using inheritance, we can use the module to re-use code.

module Driveable
  def drive
    p 'driving'
  end
end

class Car
  include Driveable
end

car = Car.new
car.drive

We define a Driveable module with drive method. The include statement inside the Car class mixes in the Driveable module into the Car class. We can instantiate the car object and send the drive message to it. This prints:

driving

This is the mixin concept.

Mixing Single Module

Mixin Multiple Modules

We can mixin multiple modules to our Car class.

module Driveable
  def drive
    p 'driving'
  end
end

module Stopable
  def stop
    p 'brake failure, cannot stop'
  end  
end

class Car
  include Driveable
  include Stopable
end

car = Car.new
car.drive
car.stop

We create a car object and we can call any of the methods that is available in the mixed-in modules. This prints:

driving
brake failure, cannot stop

Mixin Multiple Modules

Key Takeaway

The include statement is used to mixin methods defined in a module into a class. The mixed-in methods become instance methods in the class.

Extending a Module

What if we want a class method? We can use the extend statement to pull in the methods defined in a module as class methods in a class.

module Turnable
  def turn
    p 'turning'
  end
end

class Car
  extend Turnable
end

Car.turn

This prints:

turning

The turn method is a class method because we don't need an instance of Car class to call the turn method. We use the Car class to call the turn method.

Summary

In this article, you learned how to overcome the single inheritance limitation. You can define as many modules as you want and mixin the behavior into a class by using the include statement. We also saw how to use extend statement to re-use class methods.


Related Articles


Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.