midRuby

Explain how module inclusion works using include, prepend, and extend.

Updated May 17, 2026

Short answer

include inserts the module directly after the class in the lookup chain. prepend places the module before the class in the lookup chain. extend adds the module's methods as class methods.

Deep explanation

Ruby uses an ancestor chain to resolve methods. When you use include MyModule, Ruby injects MyModule directly above the current class in the hierarchy; if a method is in both, the class wins. prepend MyModule overrides this by injecting MyModule below the class, allowing module methods to execute first and call super to hit the class implementation. extend MyModule extends the class's singleton class, converting instance methods of the module into class methods of the target class.

Real-world example

prepend is extensively used in aspect-oriented programming and tracing gems to hook into existing methods, log metrics, and call super. extend is used for adding utility or class-level finder methods.

Common mistakes

  • Using `include` expecting the module methods to override an existing method in the target class. Since the class comes first in the lookup path, the class's own method shadows the included module's method.

Follow-up questions

  • How can you view the lookup chain of a class?
  • What module hook runs when a module is included into a class?

More Ruby interview questions

View all →