Ruby - Modules as Namespaces

Introduction

A module is like a named "wrapper" around a set of methods, constants, and classes.

The various of code inside the module share the same "namespace".

And they are all visible to each other but are not visible to code outside the module.

Ruby class library defines a number of modules such as Math and Kernel.

Math module contains mathematical methods such as sqrt to return a square route and constants such as PI.

The Kernel module contains methods such as print, puts, and gets.

Let's assume you have written this module:

module MyModule
    GOODMOOD = "happy"
    BADMOOD = "grumpy"

    def greet
        return "I'm #{GOODMOOD}. How are you?"
    end

    def MyModule.greet
        return "I'm #{BADMOOD}. How are you?"
    end
end

To call a module method, use

MyModule.greet 

To access the module constants, using ::

puts(MyModule::GOODMOOD)    #=> happy

To access the module instance method, use mixins.

Related Topic