Classes and superclasses

Dear list members,

A beginner’s question:

I wrote a simple programme that assembles exams, choosing the questions
from a database according to certain criteria. The programme does what I
want, but I realised there are certain basic things I don’t understand,
e.g.:

My programme has classes analogous to class Song and class SongList in
the pickaxe book (class Question and class QuestionList).
Class QuestionList includes the definition
def length
@questions.length
end

and that, of course, works.

When, instead of that definition, I make class QuestionList a subclass
of Array (QuestionList < Array), asking for the length doesn’t give me
an error, but returns a length of 0. So “length” doesn’t know what to do
with an instance of QuestionList, although the latter class includes

def initialize
@questions = Array.new
end
and is now a subclass of “Array”.

Why not? Thanks for answers,
Jörg

Prof.Dr.med. Jörg Hagmann-Zanolari
Institute of Biochemistry and Genetics
Centre of Biomedicine, University of Basel
Mattenstrasse 28
CH-4058 Basel
Switzerland
Phone +41 (0)61 267 3565

2008/1/21, Jörg Hagmann [email protected]:

the pickaxe book (class Question and class QuestionList).
with an instance of QuestionList, although the latter class includes

def initialize
@questions = Array.new
end
and is now a subclass of “Array”.

Why not? Thanks for answers, Jörg

You mixed “inheritance” and “delegation”. The definition of
#initialize you show above creates a member variable of class Array.
If your class inherits from Array you get two arrays, i.e. via
inheritance and via delegation. This is usually a bad idea - you
either want one or the other. With Array and Hash most of the time
delegation is better. If you use inheritance you should keep in mind
that this relationship between classes is also called “is-a”
relationship, i.e. you really get all the Array functionality. This
is often not what is wanted, because client code can manipulate the
object like an Array which might break your code in the subclass (for
example if that code relies on elements being of a particular type).

Kind regards

robert