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

Module Basics

In this page:

  1. Module Basics

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)
🔒

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.