Modules as Namespaces

You can think of a module as a sort of named “wrapper” around a set of methods, constants, and classes. The various bits of code inside the module share the same “namespace,” so they are all visible to each other but are not visible to code outside the module.

The Ruby class library defines a number of modules such as Math and Kernel. The Math module contains mathematical methods such as sqrt to return a square route and constants such as PI. The Kernel module contains many of the methods you’ve been using from the outset such as print, puts, and gets.

Let’s assume you have written this module:

modules1.rb

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

You’ve already seen how to use a module method such as MyModule.greet, and you can access the module constants just as you would access class constants, using the scope resolution operator, :: , like this:

puts(MyModule::GOODMOOD)    #=> happy

But how can you access the instance method, greet? This is where mixins enter the picture.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.246.148