← Back to Ruby Course | Chapter 10: Modules & Mixins | Lesson 1 of 6

Module Basics

A module is a named container for related methods and values, like a toolbox with a label. It is not something you make objects from, but something to share.

In this page:

  1. Module Basics
Syntax
ruby
module ModuleName
  CONSTANT = value

  def self.method_name
    # body
  end
end

ModuleName.method_name

Module Basics

A module is defined with module ModuleName ... end, grouping related methods, constants, and classes together, similar to a class but without the ability to be instantiated with .new.

Modules serve two main purposes: namespacing (organizing related code) and mixins (sharing behavior across classes). They're a core part of how Ruby avoids needing multiple class inheritance.

Note: Trying to call SomeModule.new raises a NoMethodError -- modules cannot be instantiated directly, unlike classes.

Example: Module Basics

markup
module MathHelpers
  def self.square(n)
    n * n
  end
end

puts MathHelpers.square(6)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Defining def square without self. and calling MathHelpers.square, which raises NoMethodError.
  2. Naming a module in lowercase such as module math_helpers, which is a syntax error because module names must be constants starting with a capital letter.
  3. Trying MathHelpers.new, which raises NoMethodError because a module cannot be instantiated.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.