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.
Syntax:
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 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.
Ruby
# Ruby program to illustrate namespace # Defining a namespace called Geek module Geek class GeeksforGeeks # The variable gfg attr_reader :gfg # Class GeeksforGeeks constructor def initialize(value) @gfg = value end end end # Accessing the sub members of # module using '::' operator obj = Geek::GeeksforGeeks. new ( "GeeksForGeeks" ) puts obj.gfg |
Output:
GeeksForGeeks
Example 2:
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.
Ruby
# Ruby program to illustrate namespace # The main namespace module Geek class GeeksforGeeks attr_reader :gfg def initialize(value) @gfg = value end end # Hierarchical namespace module Geek_1 # Reuse of the class names class GeeksforGeeks @@var = "This is the module Geek_1 " + "and class GeeksforGeeks" def printVar() puts @@var end end end # Hierarchical namespace module Geek_2 # Reuse of the class names class GeeksforGeeks attr_reader :var def initialize(var) @var = var end end end end obj_gfg = Geek::GeeksforGeeks. new ( "This is the module Geek " + "and class GeeksforGeeks" ) obj_gfg1 = Geek::Geek_1::GeeksforGeeks. new () obj_gfg2 = Geek::Geek_2::GeeksforGeeks. new ( "This is the module Geek_2 " + "and class GeeksforGeeks" ) puts obj_gfg.gfg puts obj_gfg1.printVar() puts obj_gfg2.var |
Output:
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...