Modules and Namespaces

A Ruby module is nothing more than a grouping of objects under a single name. The objects may be constants, methods, classes, or other modules.

Modules have two uses. You can use a module as a convenient way to bundle objects together, or you can incorporate its contents into a class with Ruby's include statement.

When a module is used as a container for objects, it's called a namespace. Ruby's Math module is a good example of a namespace: it provides an overarching structure for constants like Math::PI and methods like Math::log, which would otherwise clutter up the main Kernel namespace. We cover this most basic use of modules in Recipes 9.5 and 9.7.

Modules are also used to package functionality for inclusion in classes. The Enumerable module isn't supposed to be used on its own: it adds functionality to a class like Array or Hash. We cover the use of modules as packaged functionality for existing classes in Recipes 9.1 and 9.4.

Module is actually the superclass of Class, so every Ruby class is also a module. Throughout this book we talk about using methods of Module from within classes. The same methods will work exactly the same way within modules. The only thing you can't do with a module is instantiate an object from it:

	Class.superclass # => Module
	Math.class # => Module
	# NoMethodError: undefined method `new' for Math:Module



Date and Time



Files and Directories

Code Blocks and Iteration

Objects and Classes8

Modules and Namespaces

Reflection and Metaprogramming


Graphics and Other File Formats

Databases and Persistence

Internet Services

Web Development Ruby on Rails

Web Services and Distributed Programming

Testing, Debugging, Optimizing, and Documenting

Packaging and Distributing Software

Automating Tasks with Rake

Multitasking and Multithreading

User Interface

Extending Ruby with Other Languages

System Administration

Ruby Cookbook
Ruby Cookbook (Cookbooks (OReilly))
ISBN: 0596523696
EAN: 2147483647
Year: N/A
Pages: 399 © 2008-2020.
If you may any questions please contact us: