Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What are Modules in Ruby?
2.1.
Points to Remember✍️
2.2.
Basic Syntax of Modules in Ruby🖥️
3.
Example of Modules in Ruby
3.1.
Output
4.
Module as Namespaces
5.
Modules in Mixins
6.
Frequently Asked Questions
6.1.
Whаt аre modules used for in Ruby?
6.2.
Cаn а Ruby module include аnother module?
6.3.
Cаn а module contаin а clаss in Ruby?
6.4.
Cаn Ruby modules hаve instаnce vаriаbles?
6.5.
Whаt is а module stаtement?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Modules in Ruby

Author Aditya kumar
0 upvote
gp-icon
Data structures & algorithms (Beginner to Intermediate)
Free guided path
13 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

Modules in Ruby are the grouping of constants, methods, and class variables. Module methods or instance methods can both be used in modules.

Methods in a class included in a module are known as instance methods.

While instance methods cannot be called without first building an encapsulating object, module methods can.

Since they contain a collection of methods, class definitions, constants, and other modules, they are comparable to classes. They are described similarly to classes. Modules can not be used to construct objects or subclasses. There is no hierarchy of inheritance for modules.

modules in ruby

What are Modules in Ruby?

A module is a grouping of class variables, constants, and methods. While classes are defined using the class keyword, modules are defined using the module keyword.

Points to Remember✍️

  • Modules cannot be inherited, nor can subclasses of modules be created.
     
  • A module cannot be used to build an object.
     
  • Namespaces and mixins are both utilized with modules.
     
  • All modules are classes, but not all classes are modules.
     
  • Although the class can use namespaces, unlike modules, it cannot use mixins(Ruby's mixins feature enables modules to use the include method to access the instance methods of another module).
     
  • A module's name must begin with a capital letter.
     

Modules primarily have two functions:

  1. Modules act as the namespace. They avoid name conflicts.
     
  2. They make it possible for classes to share functionality via the mixin facility.

Basic Syntax of Modules in Ruby🖥️

module ModuleNameHere  
    
    # Write anything here
   ...........  
end  

A capital letter should be used to begin the module name, here, we have taken the module name as ‘ModuleNameHere’.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Example of Modules in Ruby

Here is a simple example of modules in Ruby which is mentioned below:

module CodingNinjas  

    # Taking a constant C    
    C = 67;    
    # Prefix with Module name
    # Method Name
    def CodingNinjas.mainpage
        puts "Home Page of Coding Ninjas"
    end
        
    # Prefix with Module name
    # Method Name
    def CodingNinjas.buycourses
        puts "You can buy any course!"
    end

    # Prefix with Module name
    # Method Name
    def CodingNinjas.articles  
        puts "Topic of this article is Modules in Ruby"
    end      
end 
  
# Displaying module constant's value
puts CodingNinjas::C

# Method Calling
CodingNinjas.mainpage
CodingNinjas.buycourses
CodingNinjas.articles

Output

Output

In the above example, we can point out some important things which are given below:

👉🏻 When defining a module method, the user must precede the method name with the name of the module. The advantage of defining a module method is that a user can call it simply by using the module name and dot operator, as in the example above.

👉🏻 The double-colon operator (::), as demonstrated in the example above, allows a user to retrieve the value of a module constant.

👉🏻 If a user simply uses the def keyword to define a method inside of a module, such as the def method name, then that method will be regarded as an instance method. 

👉🏻 Since a user cannot create an instance of the module, therefore cannot access instance methods directly with the dot operator.

👉🏻 The user must include the module inside a class and then use the class instance to access the instance method defined inside the module. The examples below clearly demonstrate this idea.

👉🏻 By using the keyword include, the user can use the module inside the class. The module functions in this instance like a namespace.

Module as Namespaces

Larger files are written with a lot of reusable codes. Classes have been created from these codes, which may be put into a file.

Suppose, for instance, two people each have the same method name in a different file. Additionally, a third file must contain both of the other files. As the method nаme in both included files is the same, this could lead to an issue.

The module mechanism is used in this situation. The namespace that modules define allows you to specify your methods and constants without worrying about them conflicting with those of other modules.

For Example:

Assume that we have specified various cars in a company, such as sports, royal, etc., in ‘data1.rb’.

The number of cars that are tested or non-tested for a drive, including sports, is defined in ‘data2.rb’.

We must load both files data1 and data2 in ‘data3.rb’. In this case, we'll employ a module mechanism.

data1.rb

#!/usr/bin/ruby     
# Module defined in data1.rb file     
module Cars   
   num_of_car = 300   
   def Cars.sports(120)   
   # ..   
   end   
   def Cars.royal(180)   
   # ..   
   end   
end 

data2.rb

#!/usr/bin/ruby   
# Module defined in data2.rb file    
module TestCars   
   total = 123   
   tested = 25   
   def TestCars.sports(nontested)   
   # ...   
   end   
end 

data3.rb

require "Cars"   
require "TestCars"   
  
x = Cars.sports(Cars::num_of_car)   
y = TestCars.sports(TestCars::total) 

We reference a constant using the module name and two colons, and invoke a module method by prefixing its name with the module's name and a period.

Modules in Mixins

Ruby doesn't allow for more than one inheritance. Using mixin in Ruby, modules can remove necessity for multiple inheritаnce.

Since a module is not a class, it lacks instances. Nevertheless, a class may contain a module.

The class will have access to the module's methods if you include a module inside.

Example

module CarName   
   def swift  
   end   
   def alto  
   end   
end   

module Feature   
   def price   
   end   
   def mileage   
   end   
end   
  
class Both   
include CarName   
include Feature  
   def f   
   end   
end   
  
final=Both.new   
final.swift  
final.alto   
final.price   
final.mileage  
final.f     

Here, module ‘CarName’ consists of methods ‘swift’ and ‘alto’. Module ‘Feature’ consists of methods ‘price’ and ‘mileage’. The class ‘Both’ includes both the modules due to which class ‘Both’ can access all the four methods. Hence, class ‘Both’ works as a mixin.

Both instance methods and class methods may be included in a module's methods that are blended into a class depending on how we incorporate mixin into the class. This above example shows multiple inheritance using mixins in Ruby.

The actions taken by the ‘require’ and ‘include’ methods differ significantly.

  • The require method runs a different file, just like include does in most other programming languages. Additionally, it keeps track of previous requests so that you won't need the same file more than once. You can use the load method to run a different file without this extra capability.
     
  • The include method imports into the current module all the methods from another module. As contrast to need, this is a language-level issue rather than a file-level issue. The primary approach for "extending" classes with other modules is the include method (usually referred to as mix-ins).

Frequently Asked Questions

Whаt аre modules used for in Ruby?

Modules аre а wаy of grouping together methods, clаsses, аnd constаnts. Modules give you two mаjor benefits. Modules provide а nаmespаce аnd prevent nаme clаshes.

Cаn а Ruby module include аnother module?

Yes, Ruby fаcilitаtes the use of composition by using the mixin fаcility. 

Cаn а module contаin а clаss in Ruby?

A Ruby module cаn contаin clаsses аnd other modules, which meаns you cаn use it аs а nаmespаce.

Cаn Ruby modules hаve instаnce vаriаbles?

Yes, Module instаnce vаriаbles аre present in the clаss when you would include them inside the clаss.

Whаt is а module stаtement?

A Module stаtement defines а reference type аvаilаble throughout its nаmespаce. A module (sometimes cаlled а stаndаrd module) is similаr to а clаss but with some crucial distinctions.

Conclusion

In this article, we have discussed modules in Ruby. We have discussed why we use modules and their implementation of them in Ruby. We have also discussed namespaces and mixins in modules with the help of simple examples.

We hope this blog has helped you enhance your knowledge regarding Modules in Ruby. To learn more, check out our articles on Loading and Requiring Modules in rubyAccessors and Attributes of class in RubyWriting an Inherited Class in ruby, and Ordering Points in Ruby.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available; look at the Top 150 Interview Puzzles interview experiences, and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow. 

Thank you

Happy Learning Ninja!

Previous article
Classes and Modules in Ruby
Next article
Ruby Surprises
Guided path
Free
gridgp-icon
Data structures & algorithms (Beginner to Intermediate)
13 chapters
109+ Problems
gp-badge
Earn badges and level up
Live masterclass