What is Module in Ruby: Definition, Usage, and Examples
module is a way to group related methods, constants, and classes together without creating an instance. Modules help organize code and can be mixed into classes to share behavior using include or extend.How It Works
Think of a Ruby module like a toolbox that holds useful tools (methods and constants) you want to share but don't want to turn into a full object on its own. Unlike classes, you cannot create objects directly from modules. Instead, modules act as containers for code that can be reused in different places.
When you want to add the tools from a module into a class, you can include the module, which mixes its methods as instance methods of the class. Alternatively, you can extend a class or object with a module to add methods as class methods. This helps avoid repeating code and keeps your program organized.
Example
This example shows a module with a method that can be shared by different classes.
module Greetings
def greet
"Hello!"
end
end
class Person
include Greetings
end
class Robot
include Greetings
end
p = Person.new
r = Robot.new
puts p.greet
puts r.greetWhen to Use
Use modules when you want to share common behavior across multiple classes without using inheritance. For example, if several classes need the same helper methods or constants, put them in a module and include it where needed.
Modules are also useful for organizing code into namespaces to avoid name clashes. They help keep your code clean, reusable, and easier to maintain.
Key Points
- Modules group related methods and constants without creating objects.
- You cannot instantiate a module directly.
- Use
includeto add module methods as instance methods in a class. - Use
extendto add module methods as class methods. - Modules help share code and organize namespaces.