Modules in Ruby Language

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

/wiki/Ruby_(programming_language)">Ruby, one of the tools that helps achieve this modularity is the module. Modules are an essential part of Ruby’s object-oriented programming paradigm, and they play a crucial role in code organization, reuse, and encapsulation.

What is a Module in Ruby?

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:

  1. Namespace: Modules provide a way to create a separate namespace for methods and constants, preventing naming conflicts. This is especially useful when you’re working on larger projects with multiple contributors.
  2. Mixin: Modules can be used to mix behavior into classes. This allows you to add methods to multiple classes without having to duplicate code.

Creating a Module

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
end

In this example, we’ve defined a module named MyModule with a single method, greet.

Using a Module

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.greet

In this code, we’ve created a class MyClass and included the MyModule. Now, instances of MyClass can use the greet method defined in MyModule.

Real-World Use Case: Enumerable Module

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.


Discover more from PiEmbSysTech

Subscribe to get the latest posts sent to your email.

Leave a Reply

Scroll to Top

Discover more from PiEmbSysTech

Subscribe now to keep reading and get access to the full archive.

Continue reading