Module Basics

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

Single Inheritance

In the previous chapter you learned that Ruby is a single inheritance language. We can have only one parent. In this chapter, 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 chapter, 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.

results matching ""

    No results matching ""