Fiddling with Inheritance

Now let's crank it up a notch by looking at a somewhat more extended, though still small example. We'll start by doing it wrong.

Not really wrong—our example will run—but wrong in the sense that it could be done more easily and reliably with some redesign. That redesign, as you might guess, will take the form of establishing one or more relationships of inheritance among classes.

Let's say we wanted to write a set of Ruby classes to model the members of the violin family. We might reasonably start with the violin itself:

class Violin
  attr_accessor :strings

  def tuning
    %w{ g d a e }
  end

  def tune
    @strings = self.tuning
  end

  def untune
    @strings = false
  end

  def in_tune?
    @strings
  end
end

To represent the tuning of a violin's ...

Get Sams Teach Yourself Ruby in 21 Days now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.