4.6. Modules and Mixins

The word "module" has been mentioned here and there a few times so far. It's time to take a closer look at a fundamental part of Ruby programming.

As mentioned before, modules serve two purposes. They act as namespaces that prevent name collision and are used as a way to add functionalities to classes that would otherwise be limited by the single inheritance nature of Ruby's object model.

A series of similarities between classes and modules are as follows:

  • Classes are constants and so are modules.

  • Classes are defined through the class keyword and modules are defined with the module keyword.

  • Classes are instances of the Class class, and modules are instances of the Module class.

  • Classes act as namespaces. Two identical methods defined within two unrelated classes are not going to pose a problem. The same is true for modules.

  • Classes can be nested, and so can modules.

  • The Class class inherits from the Module class, so it can be said that every class is also a module.

On the other hand, a few fundamental differences also exist:

  • Classes can be instantiated. Modules cannot.

  • Classes can have a superclass and subclasses; as such they yield a hierarchy tree. Modules do not, because they don't have a parent or any children.

  • Modules can be used as mixins, but classes cannot.

4.6.1. Modules Act as Namespaces

If you are a .NET developer, you are no doubt familiar with the concept of namespaces. The basic idea is to group constants, variables, methods, and classes into well-organized ...

Get Ruby on Rails® for Microsoft Developers 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.