Ruby

• Know About Different Blocks in Ruby • Know More About Different Modules in Ruby • Know About Exceptions in Ruby • Know More About Different Methods in Ruby • Know About Ruby Class • Know About Ruby File I/O • Know More About Different Iterators in Ruby • Know About Control Structures in Ruby • Know About Hashes in Ruby • Know About Different Arrays in Ruby • Know More About Operators in Ruby • Know About Various Datatypes/Literals in Ruby • Know About Variables in Ruby | Learning Hub • Know More About Installation of Ruby on rails (using rbenv) • Know More About Ruby

10 lessons

Lessons

2 of 10

Know More About Different Modules in Ruby

Modules in Ruby | Learning Hub | OdinSchool


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.