0
0
RubyHow-ToBeginner · 3 min read

How to Use Module in Ruby: Syntax and Examples

In Ruby, you use a module to group related methods and constants. Define a module with module ModuleName and include it in classes using include ModuleName to share its methods.
📐

Syntax

A module is defined with the keyword module followed by the module name. Inside, you can define methods and constants. To use the module's methods in a class, use include ModuleName. This adds the module's methods as instance methods of the class.

ruby
module Greetings
  def say_hello
    "Hello!"
  end
end

class Person
  include Greetings
end
💻

Example

This example shows how to define a module with a method and include it in a class to use that method.

ruby
module Greetings
  def say_hello
    "Hello!"
  end
end

class Person
  include Greetings
end

person = Person.new
puts person.say_hello
Output
Hello!
⚠️

Common Pitfalls

One common mistake is trying to call module methods directly without including or extending the module. Also, using include adds methods as instance methods, but to add them as class methods, you need extend.

Another pitfall is naming conflicts when multiple modules define the same method.

ruby
module Greetings
  def say_hello
    "Hello!"
  end
end

class Person
  # Wrong: calling module method directly without include
  # puts say_hello # This will cause an error

  # Right: include module to use instance methods
  include Greetings
end

person = Person.new
puts person.say_hello
Output
Hello!
📊

Quick Reference

  • Define module: module ModuleName ... end
  • Include module in class: include ModuleName (adds instance methods)
  • Extend module in class: extend ModuleName (adds class methods)
  • Call module methods: After including, call as instance methods

Key Takeaways

Use module to group reusable methods and constants in Ruby.
Include a module in a class with include to add instance methods.
Use extend to add module methods as class methods.
You cannot call module methods directly without including or extending.
Watch out for method name conflicts when mixing multiple modules.