Ruby: What extend and include do

All Rubyists should be familiar with the common definitions for include and extend. You include a module to add instance methods to a class and extend to add class methods. Unfortunately, this common definition isn’t entirely accurate. It fails to explain why we use instance.extend(Module) to add methods to an instance. Shouldn’t it be instance.include(Module)? To figure this out we’re going to start by discussing where methods are stored.

  • include: Adds methods from the provided Module to the object
  • extend: Calls include on the singleton class of the object

Further reading

After you understood include and extend you might want to look into more Ruby metaprogramming basics:

Dominik Schöler About 11 years ago