8.1 Getting Modular

Mixing it up

Ruby modules allow you to create groups of methods that you can then include or mix into any number of classes. Modules only hold behaviour, unlike classes, which hold both behaviour and state.

Since a module cannot be instantiated, there is no way for its methods to be called directly. Instead, it should be included in another class, which makes its methods available for use in instances of that class. There is, of course, more to this story, but let's keep it simple for now.

In order to include a module into a class, we use the method include which takes one parameter - the name of a Module.

Example Code:

Output Window

In the example above, we have a Gym and a Dojo. They each have their own, distinct behaviour - preacher_curls and tai_kyo_kyu respectively. However, both require push_ups, so this behaviour has been separated into a module, which is then included into both classes.

Some hierarchy and a little exercise

Just like all classes are instances of Ruby's Class, all modules in Ruby are instances of Module.

Interestingly, Module is the superclass of Class, so this means that all classes are also modules, and can be used as such. For detailed lessons on inheritance in Ruby, do take a look at our chapter on the subject in the "Ruby Primer: Ascent."

Example Code:

Output Window

Time for some practice! As always, make the tests pass. Note that the perimeter of both a square and a rectangle is calculated by summing up all of its sides.

Output Window

Congratulations, guest!

% of the book completed


This lesson is Copyright © 2011-2015 by Sidu Ponnappa and Jasim A Basheer