Pickaxe Book Chapter 05

This chapter is about inheritance, modules and mixins.

To make a subclass:

class Child < Parent

You can invoke parent class methods with “super”, just like in Java. You will usually want to call “super” in the initialize method if you are inheriting.

On page 95, it would be nice if the “private” keyword was tabbed in a few spaces.

Modules provide namespaces and allow some reusability. But unlike packages in Java it seems like they are similar to Ruby classes with two differences:
1. They have the word “module” in front of the name instead of the word “class”
2. Methods defined in the module have the module name in front of them. So if a Trigonometry class had a method “sin(x)” tyou would see this:

class Trigonometry
    # This is a constant
    PI = 22/7
    def sin(x)
        # implementation
    # other stuff

A module would do it like this:

module Trigonometry
    def Trigonometry.sin(x)
        # implementation
    # other stuff

If you use a module constant, you need to specify the module name and use the double-colon operator:

y = Trigonometry.sin(Trigonometry::PI/2)

Modules cannot have instances, so I guess they are like static classes in Java.

Is there inheritance for modules? I may find out

A mixin is when you include a module in a class. Then you can call the module’s method from a class instance as if they were parent methods.

The book talks quite a bit about the Enumerable mixin. I guess all you have to do is provide an “each” method, and you get all the iteration methods in collections (Array and Hash).

At the end of the chapter, they recommend designing programs with composition (has-a) and delegation (uses-a) instead of inheritance (is-a). They seem to say that mixins are more of a composition technique than an inheritance technique.

Image from Wikimedia, assumed allowed under Fair Use. Image from the Ambrosian Iliad, a 5th century manuscript of the Iliad.

There are 322 words in this article.