What is Namespace in Ruby: Explanation and Examples
namespace is a way to group related classes, modules, or constants under a named module to avoid name conflicts. It works like a container that keeps your code organized and prevents clashes between identically named items.How It Works
Think of a namespace in Ruby as a labeled box where you keep related things together. Just like you might have a box labeled "Toys" and another labeled "Books" to keep your room tidy, namespaces keep your code organized by grouping related classes or modules inside a module.
This grouping helps avoid confusion when two parts of your program use the same name for different things. By putting them in different namespaces (modules), Ruby knows exactly which one you mean.
Namespaces are created using module keywords. Inside a module, you can define classes, methods, or constants that belong only to that module. To use them outside, you refer to them with the module name as a prefix, like an address.
Example
This example shows two classes with the same name inside different namespaces to avoid conflict.
module Animals class Dog def speak "Woof!" end end end module Robots class Dog def speak "Beep boop!" end end end puts Animals::Dog.new.speak puts Robots::Dog.new.speak
When to Use
Use namespaces in Ruby when you want to organize your code clearly and avoid name clashes. For example, if you are building a large app with many classes, namespaces help keep related classes grouped logically.
Namespaces are especially useful when integrating different libraries or modules that might have classes or methods with the same names. By placing them in separate modules, you prevent conflicts and make your code easier to maintain.
Key Points
- Namespaces in Ruby are created using
module. - They group related classes, methods, and constants.
- Namespaces prevent name conflicts by providing a unique context.
- Access namespaced items using the
::operator. - They help keep large codebases organized and maintainable.