Ruby Keyword: module - rking/pry-docmore GitHub Wiki
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:
-
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.
-
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