Skip to Content
Ruby on Rails® for Microsoft Developers
book

Ruby on Rails® for Microsoft Developers

by Antonio Cangiano
April 2009
Intermediate to advanced content levelIntermediate to advanced
479 pages
12h 55m
English
Wrox
Content preview from Ruby on Rails® for Microsoft Developers

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Ruby on Rails™ 3 Tutorial: Learn Rails™ by Example

Ruby on Rails™ 3 Tutorial: Learn Rails™ by Example

Michael Hartl

Publisher Resources

ISBN: 9780470374955Purchase book