O'Reilly logo

Sams Teach Yourself Ruby in 21 Days by Mark Slagell

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required