Module Methods

In addition to instance methods, a module may also have module methods. Just as class methods are prefixed with the name of the class, module methods are prefixed with the name of the module:

def MyModule.lose
    return "Sorry, you didn't win"
end

You can call a module’s module methods just as you would call a class’s class methods, using dot notation, like this:

MyModule.lose   #=> "Sorry, you didn't win"

But how do you call an instance method? Neither of the following attempts succeeds:

puts( prize )           # Error: undefined local variable or method
puts( MyModule.prize )  # Error: undefined method 'prize'

In spite of their similarities, classes possess two major features that modules do not: instances and inheritance. Classes can have instances (objects created from the class), superclasses (parents), and subclasses (children); modules can have none of these. It is not possible to call an instance method from an instance of a module (a “module object”) for the simple reason that it is impossible to create instances of a module. This explains the errors when you try to call the prize method in the previous code.

Note

The Module class does have a superclass, namely, Object. However, any named modules that you create do not have superclasses. For a more detailed account of the relationship between modules and classes, see Digging Deeper in Digging Deeper.

That leads me to the next question: If you can’t create an object from a module, what are modules for? This can be answered in two words: namespaces and mixins. Ruby’s mixins provide a way of dealing with the problem of multiple inheritance. You’ll learn how mixins work shortly. First, though, let’s look at namespaces.