Modules

Like a class, a module is a named group of methods, constants, and class variables. Modules are defined much like classes are, but the module keyword is used in place of the class keyword. Unlike a class, however, a module cannot be instantiated, and it cannot be subclassed. Modules stand alone; there is no “module hierarchy” of inheritance.

Modules are used as namespaces and as mixins. The subsections that follow explain these two uses.

Just as a class object is an instance of the Class class, a module object is an instance of the Module class. Class is a subclass of Module. This means that all classes are modules, but not all modules are classes. Classes can be used as namespaces, just as modules can. Classes cannot, however, be used as mixins.

Modules as Namespaces

Modules are a good way to group related methods when object-oriented programming is not necessary. Suppose, for example, you were writing methods to encode and decode binary data to and from text using the Base64 encoding. There is no need for special encoder and decoder objects, so there is no reason to define a class here. All we need are two methods: one to encode and one to decode. We could define just two global methods:

def base64_encode
end

def base64_decode
end

To prevent namespace collisions with other encoding and decoding methods, we’ve given our method names the base64 prefix. This solution works, but most programmers prefer to avoid adding methods to the global namespace when possible. A better solution, ...

Get The Ruby Programming Language now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.