0
0
RubyConceptBeginner · 3 min read

What is Module in Ruby: Definition, Usage, and Examples

In Ruby, a 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.

ruby
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.greet
Output
Hello! Hello!
🎯

When 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 include to add module methods as instance methods in a class.
  • Use extend to add module methods as class methods.
  • Modules help share code and organize namespaces.

Key Takeaways

A Ruby module groups reusable methods and constants without creating instances.
Modules can be mixed into classes using include or extend to share behavior.
Modules help avoid code duplication and organize your program.
You cannot create objects directly from a module.
Use modules to add shared functionality across different classes.