Thursday, May 31, 2012

What are ruby modules and how do they work?

A ruby module is basically a container for constants and methods. It is sort of a mix between structures in languages like C and C++ and interfaces in Java (because it can be mixed in to simulate multiple inheritance - more on that later). Using a ruby module works very well for resolving namespace conflicts and promoting a well abstracted program design.

To define a ruby module, you type module MyModule. Modules must begin with an uppercase letter, I believe. Just as with a class, you end the module definition with the end keyword. Inside a module, you can define constants (which must also start with a capital letter) and functions with the def statement. An important note: you can define constants in MyModule by just writing CONSTANT = 5 or the like, but you must define methods by prefixing their names with the module name and a dot as in MyModule.function.

When you have defined a module, you can access its constants with the :: operator as in MyModule::CONSTANT and its functions with MyModule.function (the . operator). Here's a full example (with albeit stupid outputs):

module OneThing
VALUE = 24
def OneThing.function
puts 'this is the first thing'
end
end
module TwoThing
VALUE = 25
def TwoThing.function
puts 'this is the second thing'
end
end

puts OneThing::VALUE.to_s
OneThing.function

puts TwoThing::VALUE.to_s
TwoThing.function

This will output:

24
this is the first thing
25
this is the second thing

So that's how modules work in ruby. More on mixing in modules later when we talk about inheritance and multiple inheritance.

No comments:

Post a Comment