0
0
RubyHow-ToBeginner · 3 min read

How to Extend Module in Ruby: Syntax and Examples

In Ruby, you can extend a module into a class or object using the extend keyword to add the module's methods as class methods. This means the methods become available on the class itself, not just on instances.
📐

Syntax

The extend keyword is used to add a module's methods as class methods to a class or as singleton methods to an object.

  • extend ModuleName: Adds module methods as class methods.
  • Used inside a class or on an object.
ruby
module Greetings
  def hello
    "Hello from module!"
  end
end

class Person
  extend Greetings
end

puts Person.hello
Output
Hello from module!
💻

Example

This example shows how to extend a module into a class so the module's methods become class methods. The hello method is called directly on the class.

ruby
module MathHelpers
  def square(x)
    x * x
  end
end

class Calculator
  extend MathHelpers
end

puts Calculator.square(5)
Output
25
⚠️

Common Pitfalls

A common mistake is to use include when you want class methods. include adds module methods as instance methods, not class methods. To add class methods, use extend.

Also, extending an object adds methods only to that object, not to its class.

ruby
module Tools
  def tool_name
    "Hammer"
  end
end

class Worker
  include Tools  # Wrong if you want class methods
end

# puts Worker.tool_name  # Error: undefined method

# Correct way:
class Worker
  extend Tools
end

puts Worker.tool_name  # Outputs: Hammer
Output
Hammer
📊

Quick Reference

Use this quick guide to remember how extend works:

ActionEffect
extend ModuleName in classAdds module methods as class methods
include ModuleName in classAdds module methods as instance methods
object.extend(ModuleName)Adds module methods as singleton methods to that object

Key Takeaways

Use extend to add module methods as class methods to a class.
include adds module methods as instance methods, not class methods.
Extending an object adds methods only to that specific object.
Remember to call extended methods on the class or object, not on instances when using extend.