Modules

Modules are a way of grouping together methods, classes, and constants. Modules give you two major benefits:

  • Modules provide a namespace and prevent name clashes.
  • Modules can be included in other classes, a facility known as a mixin.

Namespaces

As you start to write bigger Ruby programs, you’ll find yourself producing chunks of reusable code—libraries of related routines that are applicable in many different contexts. You’ll want to break this code into separate files so the contents can be shared among different Ruby programs.

Often this code will be organized into classes, so you’ll probably stick a class into each file. But sometimes you want to group things together that don’t naturally form a class—for example, the methods that you ...

Get Programming Ruby 3.3 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.