Modules in Ruby

Modules in Ruby

A module in Ruby is a collection of methods and constants. The scope of these methods or constants is limited to the module they are declared in. 

Let us explore what we can do with modules.

If we look at the program described below:

module Coffee
  def cappuccino
    puts "cappuccino!"
  end
end
module Tea
  def chai
    Puts “chai!”
  End
end
class Beverage
  include Coffee
  Include Tea
  def soda
    puts "soda!"
  end
end
b = Beverage.new
b.cappuccino     # => "cappuccino!"
b.chai           # => "chai!"
b.soda           # => “soda!”

With the object ‘b’ of class ‘Bird’, we can now access both methods, flippers and wings. 

This is made possible by the usage of the include keyword that evaluates the module code in the context of the class.

Modules and Class Composition
If we look at the example mentioned above, we see that a single class has included more than one module. Effectively giving object b access to methods of more than one module apart from its own methods.

Using Extend

module Coffee
  def cappuccino
    puts "cappuccino!"
  end
end
class Beverage
  extend Coffee
  def soda
    puts "soda!"
  end
end
b = Beverage.new
b.cappuccino     # => "NoMethodError"
b.soda           # => “soda!”
Beverage.cappuccino # => “cappuccino!”

The keyword extends adds the methods of the module as the class methods.