Chapter 12. Modules and Mixins

image with no caption

In Ruby, each class has only one immediate “parent,” though each parent class may have many “children.” By restricting class hierarchies to a single line of descent, Ruby avoids some of the problems that may occur in those programming languages (such as C++) that permit multiple lines of descent. When classes have many parents as well as many children and when their parents and children also have other parents and children, you risk ending up with an impenetrable network (a knotwork?) rather than the neat, well-ordered hierarchy that you may have intended.

Nevertheless, sometimes it is useful for classes that are not closely related to implement some shared features. For example, a Sword might be a type of Weapon but also a type of Treasure; a PC might be a type of Computer but also a type of Investment; and so on. But, since the classes defining Weapons and Treasures or Computers and Investments descend from different ancestor classes, their class hierarchy gives them no obvious way of sharing data and methods. Ruby’s solution to this problem is provided by modules.

A Module Is Like a Class . . .

The definition of a module looks very similar to the definition of a class. In fact, modules and classes are closely related; the Module class is the immediate ancestor of the Class class. Just like a class, a module can contain constants, methods, and classes. Here’s a simple module:

simple_module.rb

module MyModule
    REWARD = 100

    def prize
        return "You've won #{REWARD} credits"
    end

end

As you can see, this contains a constant, REWARD, and an instance method, prize.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.73.127