Ruby modules are powerful tools for organizing and sharing code across your Ruby programs. They serve as containers for methods, constants, and classes, promoting code reusability and maintainability.
Modules in Ruby are similar to classes, but they cannot be instantiated. They provide a way to group related functionality without creating objects. This makes them ideal for:
To define a module, use the module
keyword followed by the module name in CamelCase:
module MyModule
def self.module_method
puts "This is a module method"
end
def instance_method
puts "This is an instance method"
end
end
There are several ways to use modules in Ruby:
Call module methods directly on the module:
MyModule.module_method # Output: "This is a module method"
Use the include
keyword to add instance methods from a module to a class:
class MyClass
include MyModule
end
obj = MyClass.new
obj.instance_method # Output: "This is an instance method"
The extend
keyword adds module methods as class methods:
class AnotherClass
extend MyModule
end
AnotherClass.module_method # Output: "This is a module method"
Modules are excellent for organizing code and avoiding naming conflicts. This is particularly useful in large projects or when creating libraries:
module Animals
class Dog
def bark
puts "Woof!"
end
end
end
module Robots
class Dog
def bark
puts "Beep boop!"
end
end
end
Animals::Dog.new.bark # Output: "Woof!"
Robots::Dog.new.bark # Output: "Beep boop!"
To deepen your understanding of Ruby modules, explore these related topics:
By mastering Ruby modules, you'll be able to write more organized, maintainable, and reusable code. They are a fundamental concept in Ruby programming and are widely used in both small scripts and large applications.