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:
Syntax
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
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
Login to try C/C++/Java/PHP code in the editor
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
- Writing
Circle.new(3)outside the module, which raisesNameError; useShapes::Circle.new(3). - Using
.instead of::for constants, as inShapes.Circle, which is aNoMethodError. - Defining
Circletwice 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: