← All languages
Ruby method of the day
Random

extend

Add a module's methods as class methods or singleton methods.

Description

The extend method adds a module's instance methods as singleton methods of the receiver. When called on a class, the module methods become class-level methods. When called on an instance, they become methods specific to that object.

This is different from include, which adds module methods as instance methods. Extend is useful for adding class-level utility methods or for enriching specific objects with additional behavior.

A common Ruby pattern uses both include and extend together via the included hook: instance methods are included normally, while a ClassMethods submodule is extended to add class-level behavior.

Arguments

NameDescriptionOptional
module, ... One or more modules whose methods to add. No

Example

module ClassUtils
  def description
    "A useful class"
  end
end

class MyClass
  extend ClassUtils
end

puts MyClass.description  # "A useful class"

Reference