0Pricing
Ruby Academy · Lesson

Defining Modules

Namespaces and methods.

Namespaces and Methods

A module is a container for methods and constants. Unlike a class, you cannot create an instance of a module. Modules serve two roles: grouping code (namespacing) and sharing behavior (mixins).

module Greeter
  def self.hello
    "Hello from the module"
  end
end
puts Greeter.hello

Module Methods

Define a method with self. to call it directly on the module, like a utility function. These are often called module functions.

module MathTools
  def self.square(x)
    x * x
  end
end
puts MathTools.square(7)

All lessons in this course

  1. Defining Modules
  2. include and extend
  3. Comparable and Enumerable
  4. prepend and Method Resolution
← Back to Ruby Academy