ruby
  1. ruby-modules

Ruby Modules

Syntax

module ModuleName
  # module code goes here
end

Example

module Calculator
  def self.add(a, b)
    a + b
  end
  
  def self.subtract(a, b)
    a - b
  end
end

puts Calculator.add(2, 3)    # Output: 5
puts Calculator.subtract(5, 3)    # Output: 2

Output

5
2

Explanation

A Module is a group of methods and constants that can be used across different classes and applications in Ruby. It is similar to a class in that it can contain methods, but unlike a class, it is not meant to be instantiated. Instead, it is used as a library of sorts, to be included or "mixed in" to other classes as needed.

The module keyword is used to define a new module. The module name should start with a capital letter, by convention. The methods defined within the module are accessed using the module name, followed by a dot and the method name.

In the example above, we define a module called Calculator that contains two methods, add and subtract. We use the self keyword to define them as class methods, which means they can be called on the module itself, rather than an instance of the module.

Use

Modules are used for organizing code, as well as for sharing code between multiple classes in a Ruby application. They are especially useful for defining methods that operate on data structures or perform specific tasks that can be reused across multiple classes.

To use a module, you can simply include it in another class using the include keyword, followed by the module name:

class MyClass
  include MyModule
end

This will make all the methods and constants defined in the module available within the class.

Important Points

  • Modules are used for organizing and sharing code in Ruby.
  • A module is defined using the module keyword.
  • The methods within a module are accessed using the module name, followed by a dot and the method name.
  • Modules can be included in classes using the include keyword.

Summary

In Ruby, modules are a powerful tool for organizing and sharing code. They allow you to define methods and constants once, and then use them across multiple classes and applications. By including a module in a class, you can take advantage of the methods and constants it defines, without having to write them out again from scratch.

Published on: