1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Modules

The Shortcut (With A Warning)

By

To prevent yourself from having to type module names all over the places, you can include a module into the current namespace. When you include a module, it will take all the symbols (methods, classes and constants) from the module and place them into the current namespace. It's as if they were defined in this namespace, and you no longer have to use the module name when referring to them.

You may be tempted to start doing this more often. After all, including modules into the global namespace will save on a lot of typing. This puts you right back to where you started though, if you start doing this to multiple modules, there can be potential name clashes. I usually only include modules into the current namespace if I'm using that module's vocabulary frequently, and avoid including other modules.

To include a module, use the include keyword.

 #!/usr/bin/env ruby
 
 # If your program uses methods from Math often,
 # you may want to include Math
 
 radius = 23
 
 # Without include
 a = Math.PI * radius ** 2
 
 # With include
 include Math
 a = PI * radius ** 2
 
  1. About.com
  2. Technology
  3. Ruby
  4. Beginning Ruby
  5. Ruby's Basic Features
  6. The Shortcut (With A Warning)

©2014 About.com. All rights reserved.