Home »
Ruby Tutorial
Modules in Ruby
By IncludeHelp Last updated : December 03, 2024
Modules
In Ruby, modules are similar to classes but not exactly considered as classes. You cannot instantiate a module, which simply means that you cannot create objects of modules and provide memory to them. Modules are a collection of methods, classes, and constants. Any variable declared inside a module is treated as a constant and its value can never be changed in the future. With the help of modules, you can share the methods between two classes. You only need to include them in the classes and the methods of modules become accessible to the class.
Modules provide great help when you want to make use of the same method in different classes but also wants to escape from redefining them again and again.
Syntax to Create a Module
Now, let us understand the syntax of the module first which is given below:
module Module_name
#code
end
You are supposed to use "module" keyword to define a module.
Example of a Module
Now, to have a better understanding of the concept, let us go through some of its examples which are specified below:
=begin
Ruby program to demonstrate implementation of module.
=end
module Student
Const = 100
def Student.names
puts "Your name is not available!"
end
def Student.address
puts "Your address is not available!"
end
def Student.education
puts "Education is not available!"
end
end
puts Student::Const
Student.names
Student.address
Student.education
Output
100
Your name is not available!
Your address is not available!
Education is not available!
You can observe in the above code that we are creating a module named "Student". We have defined multiple methods. To make use of module constant, you will have to use :: operator amid module name and constant.
Using a Module Inside a Class
Now, let us see how we can use a module inside a class or you can say that how to achieve one of the main objectives of the module with the help of an example provided below:
=begin
Ruby program to demonstrate implementation of module.
=end
module Student
Const = 100
def names
puts "Your name is not available!"
end
def address
puts "Your address is not available!"
end
def education
puts "Education is not available!"
end
end
class School
include Student
def gets
puts"Welcome to the school!"
end
end
obj = School.new
obj.education
obj.address
obj.names
obj.gets
Output
Education is not available!
Your address is not available!
Your name is not available!
Welcome to the school!
In the above code, you can observe that we are creating a module named as Student. Then we are creating a class named as School. We are including the Student module in the School class with the help of "include" keyword. We have instantiated the School class and then have invoked the methods of objects as well as the methods of a class with the help of that object.