Namespaces

Namespaces is a container for multiple instances which includes classes, constants and other modules. It is ensured in a namespace that all objects have unique names for their identification. It is a way of bundling logically related objects together. Modules serve as a convenient tool for this. This allows for classes or modules with conflicting names to co-exist. 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 namespace name.
  • The name of namespace and classes always start from a capital letter.
  • We can access the sub members of double with the help of :: operator. It is also called the constant resolution operator.
  • Ruby allows nested namespace.
  • We 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


  Example 1:
 
This is an example of the simple formation of the namespace with a class and then executing to 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.

Comments

Add a comment

Back to Home Page