Your first inheritance
Now that we've understood inheritance works, lets do some of our own.
Pay special attention to the syntax - the <
operator informs Ruby that when creating the class MyArray
, it should set Array
as its superclass.
Here, we've created our very own MyArray
which subclasses Ruby's Array
. It inherits all of Array
's behaviour and so has all of the same methods - and an instance of MyArray
works exactly like an instance of Array
.
This is however a poor example - MyArray
however offers us no additional behaviour over Array
and so gives us no real value.
Let's shift gears and revisit an example from the introduction to classes in the "Ruby Primer" to make this lesson more practical.
If you run the example above, you'll notice that the first test talks about a square. A square, by definition, is simply a rectangle where all sides are of equal length.
The current mechanism of creating a square - creating a rectangle and passing in the same value twice - is annoying. Lets just build our own Square class that takes just one parameter to the constructor (initialize
) instead of two, but inherits perimeter
from Rectangle
.
This way, you get a nicer syntax for squares (Square.new(3)
, say) and you get perimeter
for free from Rectangle
.