We’ve already seen how modules can be used to mix-in common behavior into classes. Now we’ll see two more uses for modules.
The first case we’ll discuss is using modules for namespacing.
In this context, namespacing means organizing similar classes in a module. In other words, we’ll use modules to group related classes.
We defined a module Mammal which groups together two classes, Dog and Cat.
Now we can call classes in the module by appending the class name to the module name with two colons(::):
a = Mammal::Dog.new
b = Mammal::Cat.new
a.speak # “Woof”
b.speak # “Meow”
Another use for modules is as containers for methods.
This allows us to group together relevant methods and use them in our code.
PI = 3.14
(1..x).inject(:*) || 1
The code above defines a module called MyMath, which includes a constant called PI, and three class methods. The methods inside a module are defined as class methods (note the self keyword), and we call them using the dot syntax.
You can call the methods using two colon syntax (::) as well (MyMath::factorial(8)), but the dot syntax is preferred.
CLICK ON THE BUTTON BELOW TO GO TO THE RUBY MAIN COURSE PAGE.
© License: All Rights Reserved
CONTACT HOLLA TECH – LEARN SUPPORT