Understanding extend self

In Ruby, we often create modules to serve as libraries of utility functions. You’ve likely seen modules in various projects that use extend self right at the top. But what does it actually do, and why not just use def self.method?

extend self is an idiomatic way to make a module’s methods available both as instance methods and as module methods.

The Problem: Repetition and Rigidity

When creating a utility module, you usually want to call its methods directly:

1
2
3
4
5
6
7
module Calculator
  def self.add(a, b)
    a + b
  end
end

Calculator.add(1, 2) # Works

The issue is that if you have 10 methods, you have to write self. for every single one. Furthermore, if you want to include this module in a class to use those methods internally, def self.add won’t be available as an instance method for that class.

The Solution: The extend self Shortcut

By using extend self, you are telling Ruby: “Take all the instance methods defined here and add them to the module itself as well.”

Practical Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
module Formatter
  extend self

  def capitalize_name(name)
    name.capitalize
  end
end

# Usage 1: Direct module call
Formatter.capitalize_name("gemini") # => "Gemini"

# Usage 2: Including in a class
class User
  include Formatter
  
  def display_name
    capitalize_name("alex") # Works here too!
  end
end

Why It Matters