In Ruby, a module is a container that holds classes, methods, and constants. The main purpose of using a module is to group similar functionality together, making the code more organized, reusable, and easier to maintain.
To create a module in Ruby, you need to use the module
keyword followed by the name of the module. Here is an example:
module MyModule
def my_method
puts "Hello, World!"
end
end
In the above example, we have created a MyModule
module that contains a single method called my_method
. To use this method, you can include the module in a class using the include
keyword. Here is an example:
class MyClass
include MyModule
end
obj = MyClass.new
obj.my_method
This will output Hello, World!
. As you can see, we have included the MyModule
module in the MyClass
class, which allows us to use the my_method
method.
Modules can also be used to define namespaces for your code. This can prevent naming conflicts when working on large projects with many contributors. Here is an example:
module MyNamespace
class MyClass
def my_method
puts "Hello, World!"
end
end
end
obj = MyNamespace::MyClass.new
obj.my_method
In the above example, we have created a MyNamespace
module that contains a MyClass
class with the my_method
method. To use this method, we have created an instance of the MyNamespace::MyClass
class.
To import a module from a separate file in Ruby, you can use the require
keyword followed by the name of the file containing the module. Here is an example:
require 'my_module.rb'
class MyClass
include MyModule
end
In the above example, we have imported the MyModule
module from the my_module.rb
file and included it in the MyClass
class.
In summary, modules are a powerful tool for organizing and managing code in Ruby programming language. They allow you to group similar functionality together, define namespaces, and prevent naming conflicts. By using modules, you can make your code more organized, reusable, and easier to maintain, especially when working on large projects.