programming ruby - 5
1, module
?
If a third programwants to use these modules, it can simply load the two files (using the Ruby require statement, which we discuss on page 116) and reference the qualified names.
?
At a stroke, they pretty much eliminate the need for multiple inheritance, providing a facility called a mixin.
?
A module can’t have instances, because a module isn’t a class. However, you can include a module within a class definition. When this happens, all the module’s instance methods are suddenly available as methods in the class as well. They get mixed in. In fact, mixed-in modules effectively behave as superclasses.
?
The Ruby include statement simply makes a reference to a named module. If that module is in a separate file, you must use require (or its less commonly used cousin, load) to drag that file in before using include. Second, a Ruby include does not simply copy the module’s instance methods into the class. Instead, it makes a reference from the class to the included module.
?
Alternativly, the module could use a module-level hash, indexed by the current object ID, to store instance-specific data without using Ruby instance variables.
?
The answer is that Ruby looks first in the immediate class of an object, then in the mixins included into that class, and then in superclasses and their mixins. If a class has multiple modules mixed in, the last one included is searched first.
?
The load method includes the named Ruby source file every time the method is executed.
?
The more commonly used require method loads any given file only once.
?
?