Modules and the Require Keyword In Ruby
What is a ruby module?
A module is a special Ruby programmatic construct that is a collection of constants and methods. It enables you to create more modular Ruby programs – you can break up large chunks of code into smaller ones.
So what are the basics of using a ruby module?
The other day a reader asked me a question regarding the use of the Ruby keyword require and the direct use of module names in a Ruby program.
The question was as follows:
1) Sometimes I see examples where we use a ‘require’ or an include for a module.
2) Sometimes we use the “module name “. ” method.name” to qualify the name of a method in a module
module Car def Car.engine_hp # ... end end
Can you please explain to me why we do this?
The reader’s confusion stemmed from the fact that it’s really 2 different use cases they were asking about
For #1, a “require” basically tells Ruby to bring in the contents of another file (typically a module; e.g., require “newexample” tells Ruby to go look for newexample.rb in its load path and allow the functionality/content of that file to be used in the current ruby environment; very analogous to an include header file statement in C++.
For #2, you are defining a method on the module “Car”. So let’s suppose you have the following lines in a “car.rb” file.
module Car def Car.engine_hp puts "engine horsepower is 170 hp" end end
Then you could call the following in a ruby script (or at the Ruby interpreter command prompt, assuming you’ve already required or defined the Car module so that Ruby knows about it): Car::engine_hp
Then you should see the output:
engine horsepower is 170 hp
You might have the following questions though…
What is the “::” symbol?
The “::” is called a scope resolution operator and it tells Ruby under what scope a name can be found under. For instance, if instead you had:
module SuperCar module Car def Car.engine_hp puts "engine horsepower is 170 hp" end end end
Then you would call SuperCar::Car::engine_hp at the Ruby interpreter command prompt.
Could I just call engine_hp by itself without using the scope resolution operator and the “Car” name prefixed in front of it?
No, you can’t. Because Ruby won’t know where to look and you’ll get an error such as the following:
`<main>’: undefined local variable or method `engine_hp’ for main:Object (NameError)
Hopefully this gives you more insight into Ruby modules and the require keyword. This is really just scratching the surface of Ruby modules, but it’s necessary knowledge if you want to keep progressing in your Ruby development.
This was a guest post. Bruce Park is a freelance web developer primarily specializing in the Ruby and Rails framework. He blogs about Ruby and Rails and other web development topics at his website, BinaryWebPark. If you’re interested in more tips for Ruby (or Rails) newbies, you might enjoy this article on serving non-static jQuery assets in your development environment.