- Ruby Modules are similar to classes in that they hold a collection of methods, constants, and other module and class definitions. Unlike classes, you cannot create objects based on modules; instead, you specify that you want the functionality of a particular module to be added to the functionality of a class, or of a specific object.
- Modules serve two purposes: First they act as namespace, letting you define methods whose names will not clash with those defined elsewhere. Second, they allow you to share functionality between classes - if a class mixes in a module, that module's instance methods become available as if they had been defined in the class. They get mixed in.
- Observe how we use require or load. require and load take strings as their arguments.
require 'motorcycle' or load 'motorcycle.rb'
include takes the name of a module, in the form of a constant, as in include 'Stuff'.
The include method accepts any number of Module objects to mix in:
include Enumerable, Comparable
Although every class is a module, the include method does not allow a class to be included within another class. - Remember that you can mix in more than one module in a class. However, a class cannot inherit from more than one class.
- Class names tend to be nouns, while module names are often adjectives.
- At every point when your program is running, there is one and only one self - the current or default object accessible to you in your program.
- Please note the rules given for self in the Self related page.
- Java features the ability to serialize objects, letting you store them somewhere and reconstitute them when needed. Ruby calls this kind of serialization marshaling.
- Marshal.dump is used to save a serialized version of an object.
- Marshal.load is used to read in from a serialized object.
- A Ruby constant is a reference to an object.
- Although constants should not be changed, you can modify the internal states of the objects they reference.
- Remember the rules for constants.
Ruby 2 Summary 8
Subscribe to:
Posts (Atom)