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

Namespacing

Namespacing wraps classes inside a module so their names do not clash, like a family name that separates two people called Sam. It keeps big programs tidy.

In this page:

  1. Namespacing
Syntax
ruby
module Namespace
  class ClassName
    # body
  end
end

Namespace::ClassName.new

Namespacing

A module can wrap classes to group related code and avoid name collisions, accessed with ::, like Shapes::Circle.

This is especially useful in larger codebases or libraries where two unrelated classes might otherwise want the same short name. Namespacing with a module is purely organizational and adds no behavior of its own.

Note: Use :: to reach into a namespacing module, like Shapes::Circle.new, distinct from . which calls a method.

Example: Namespacing

markup
module Shapes
  class Circle
    def initialize(radius)
      @radius = radius
    end

    def area
      3.14159 * @radius ** 2
    end
  end
end

circle = Shapes::Circle.new(3)
puts circle.area
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. Writing Circle.new(3) outside the module, which raises NameError; use Shapes::Circle.new(3).
  2. Using . instead of :: for constants, as in Shapes.Circle, which is a NoMethodError.
  3. Defining Circle twice in and out of the module and expecting them to be the same class.
🔒

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.