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

Get The Book of Ruby 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.