Javatpoint Logo
Javatpoint Logo

Ruby Modules

Ruby module is a collection of methods and constants. A module method may be instance method or module method.

Instance methods are methods in a class when module is included.

Module methods may be called without creating an encapsulating object while instance methods may not.

They are similar to classes as they hold a collection of methods, class definitions, constants and other modules. They are defined like classes. Objects or subclasses can not be created using modules. There is no module hierarchy of inheritance.

Modules basically serve two purposes:

  • They act as namespace. They prevent the name clashes.
  • They allow the mixin facility to share functionality between classes.

Syntax:

Module name should start with a capital letter.


Module Namespaces

While writing larger files, a lot of reusable codes are generated. These codes are organized into classes, which can be inserted into a file.

For example, if two persons have the same method name in different files. And both the files need to be included in a third file. Then it may create a problem as the method name in both included files is same.

Here, module mechanism comes into play. Modules define a namespace in which you can define your methods and constants without over riding by other methods and constants.

Example:

Suppose, in file1.rb, we have defined number of different type of library books like fiction, horror, etc.

In file2.rb, we have defined the number of novels read and left to read including fiction novels.

In file3.rb, we need to load both the files file1 and file2. Here we will use module mechanism.

file1.rb

file2.rb

file3.rb

A module method is called by preceding its name with the module's name and a period, and you reference a constant using the module name and two colons.


Module Mixins

Ruby doesn't support multiple inheritance. Modules eliminate the need of multiple inheritance using mixin in Ruby.

A module doesn't have instances because it is not a class. However, a module can be included within a class.

When you include a module within a class, the class will have access to the methods of the module.

Example:

Here, module Name consists of methods bella and ana. Module Job consists of methods editor and writer. The class Combo includes both the modules due to which class Combo can access all the four methods. Hence, class Combo works as mixin.

The methods of a module that are mixed into a class can either be an instance method or a class method. It depends upon how you add mixin to the class.

Next TopicRuby strings




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA