Namespacing
In this page:
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
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: