Namespaces in Ruby
A namespace is a container for multiple items which includes classes, constants, other modules, and more. It is ensured in a namespace that all the objects have unique names for easy identification. Generally, they are structured in a hierarchical format so, that names can be reused.
- Namespace in Ruby allows multiple structures to be written using hierarchical manner. Thus, one can reuse the names within the single main namespace.
- The namespace in Ruby is defined by prefixing the keyword module in front of the namespace name.
- The name of namespaces and classes always start from a capital letter.
- You can access the sub members of double with the help of :: operator. It is also called the constant resolution operator.
- Ruby allows nested namespace.
- You can use include keyword to copy the other module’s objects into the existing namespace without qualifying their name.
module Namespace_name # modules.. and classes.. end
This is an example of the simple formation of the namespace with a class and then executing the class methods defined within the class. Here, we access the sub members within the namespace, the “::” operator is used. It is also called the constant resolution operator.
This is an example showing the implementation of hierarchical namespacing. In this, there is a combination of class and namespace within the single namespace. Here, the use of the class name is done multiple times under the concept of hierarchical namespacing.
This is the module Geek and class GeeksforGeeks This is the module Geek_1 and class GeeksforGeeks This is the module Geek_2 and class GeeksforGeeks
Please Login to comment...