Skip to content

Ruby Keyword: module

☈king edited this page Dec 22, 2012 · 9 revisions

Usage: module ModuleName; module-contents end

Defines a new Module, or re-opens an existing module. Modules in ruby are collections of code, they have two distinct use-cases:

  1. As a Namespace. Often all of the code in a rubygem will be written in the same module to avoid naming collisions with code not in that Gem.

  2. As a set of shared functions. Modules can be included into Classes, which makes all of the methods defined in the module available to instances of the class. This can be used to emulate multiple-inheritance, or to divide one large class into more manageable chunks.

Note that, though the class Class inherits from Module, this is more of an implementation detail than a direct, Liskov-substitutable interface: modules can be included, extended or usingd, while classes cannot. (On the other hand, classes can be instantiated, where modules cannot).

module X
  def foo; 2 end
end
class Y; include X end
class Z; extend X end
# Now, these work:
Y.new.foo
Z.foo
# "extend just calls include on the eigenclass"
#   Mnemonic! INclude for INstances, Extend for sElf

For all you ever wanted to know about constant lookup, see: http://cirw.in/blog/constant-lookup

Clone this wiki locally