Modules in Ruby Language
In the world of programming, modularity is a key concept. It allows developers to break down complex systems into smaller, more manageable pieces. In
In the world of programming, modularity is a key concept. It allows developers to break down complex systems into smaller, more manageable pieces. In
A module in Ruby is a container for classes, methods, and constants. It’s not a class itself, but it can be used to group related code. Modules serve two primary purposes:
To define a module in Ruby, you use the module keyword, followed by the module name and a set of methods and constants enclosed in the module block. Here’s an example:
module MyModule
def greet
puts "Hello from MyModule!"
end
endIn this example, we’ve defined a module named MyModule with a single method, greet.
Modules can be included in classes using the include keyword. This process is often referred to as “mixing in” the module. Let’s see how to use our MyModule in a class:
class MyClass
include MyModule
end
obj = MyClass.new
obj.greetIn this code, we’ve created a class MyClass and included the MyModule. Now, instances of MyClass can use the greet method defined in MyModule.
One of the most famous examples of modules in Ruby is the Enumerable module. It provides a wide range of collection-oriented methods like each, map, and reduce. By including the Enumerable module in a class, you can instantly empower it with a plethora of collection-handling methods. Here’s a simple example:
class MyCollection
include Enumerable
def initialize
@data = [1, 2, 3, 4, 5]
end
def each
@data.each { |item| yield item }
end
end
collection = MyCollection.new
puts collection.map { |item| item * 2 }In this case, we included the Enumerable module in our MyCollection class and defined the each method required by Enumerable. Now, we can use map on our custom collection, just as we would with an array.
Subscribe to get the latest posts sent to your email.