Modules as Namespaces

You can think of a module as a sort of named “wrapper” around a set of methods, constants, and classes. The various bits of code inside the module share the same “namespace,” so they are all visible to each other but are not visible to code outside the module.

The Ruby class library defines a number of modules such as Math and Kernel. The Math module contains mathematical methods such as sqrt to return a square route and constants such as PI. The Kernel module contains many of the methods you’ve been using from the outset such as print, puts, and gets.

Let’s assume you have written this module:

modules1.rb

module MyModule GOODMOOD = "happy" BADMOOD = "grumpy" def greet return "I'm #{GOODMOOD}. How are you?" end def MyModule.greet ...

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.