Ruby: What extend and include do

Updated . Posted . Visible to the public. Repeats.

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
Last edit
Emanuel
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2013-04-10 07:01)