Namespacing is a way of bundling logically related objects together. Modules serve as a convenient tool for this. This allows classes or modules with conflicting names to co-exist while avoiding collisions. Think of this as storing different files with the same names under separate directories in your filesystem.
Modules can also hold classes. In this example, we'll try and define an
Array class under our
Perimeter module from the last lesson. Notice how it does not affect Ruby's
Array class at all.
We have these two classes alongside each other. This is possible because we've namespaced our version of the
Array class under the
:: is a constant lookup operator that looks up the
Array constant only in the
What happens when we don't namespace our
Because Ruby has open classes, doing this simply extends the
Array class globally throughout the program, which is dangerous and of course not our intended behaviour.
The examples above are a bit contrived for the sake of simplicity. The real problem that namespacing solves is when you're loading libraries. If your program bundles libraries written by different authors, it is often the case that there might be classes or modules defined by the same name.
We're assuming these two libraries
dojo have classes as shown in the comment above them.
dojo library is loaded after
gym, it has overriden
gym's class definition of
Push and therefore creates an instance of
Push defined in
The way to solve this problem is to wrap these classes in appropriate namespaces using modules.