Module (Ruby)

A module is a container for methods and constants that can't be instantiated. Modules serve two roles in Ruby: as namespaces to group related code, and as mixins to share behavior across classes.

Ruby

Defined with module Name ... end, a module groups methods and constants but, unlike a class, has no instances and no inheritance of its own. Its first job is namespacing: Math::PI and JSON.parse live inside modules, preventing name clashes.

Its second job is being a mixin: include a module into a class to add its methods as instance methods (this is how Enumerable and Comparable work). module_function or def self.method makes module-level methods callable directly, like Math.sqrt.

Use a module (not a class) when you have a bundle of related functionality or constants but no concept of 'an instance of it'. Use a class when you need to create objects with state.

Syntax

module Geometry
  PI = 3.14159
  def self.circle_area(r); PI * r * r; end
end

Examples

Ruby

module MathTools
  def self.double(x); x * 2; end
  GREETING = "hello"
end

puts MathTools.double(21)
puts MathTools::GREETING

Output:

42
hello

Learn it in a lesson

See also

Back to the Dictionary