Modules¶ ↑
Modules serve two purposes in Ruby, namespacing and mix-in functionality.
A namespace can be used to organize code by package or functionality that separates common names from interference by other packages. For example, the IRB namespace provides functionality for irb that prevents a collision for the common name “Context”.
Mix-in functionality allows sharing common methods across multiple classes or modules. Ruby comes with the Enumerable mix-in module which provides many enumeration methods based on the each method and Comparable allows comparison of objects based on the <=> comparison method.
Note that there are many similarities between modules and classes. Besides the ability to mix-in a module, the description of modules below also applies to classes.
Module Definition¶ ↑
A module is created using the module keyword:
module MyModule # ... end
A module may be reopened any number of times to add, change or remove functionality:
module MyModule def my_method end end module MyModule alias my_alias my_method end module MyModule remove_method :my_method end
Reopening modules (or classes) is a very powerful feature of Ruby, but it is best to only reopen modules you own. Reopening modules you do not own may lead to naming conflicts or difficult to diagnose bugs.
Nesting¶ ↑
Modules may be nested:
module Outer module Inner end end
Many packages create a single outermost module (or class) to provide a namespace for their functionality.