Do you think IIT Guwahati certified course can help you in your career?
No
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.
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:
Modules act as the namespace. They avoid name conflicts.
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
You can also try this code with Online Ruby Compiler
A capital letter should be used to begin the module name, here, we have taken the module name as ‘ModuleNameHere’.
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
You can also try this code with Online Ruby Compiler
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
You can also try this code with Online Ruby Compiler
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
You can also try this code with Online Ruby Compiler
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.