I’ve written an expanded version of this code in the 6dogs.rb program. This also contains a Cat class which is similar to the Dog class apart from the fact that its talk method, naturally enough, returns a miaow instead of a woof.
Oops! It seems that this program contains an error.
The object named someotherdog never has a value assigned to its @name variable. Fortunately, Ruby doesn’t blow up when we try to display this dog’s name. Instead it just prints ‘nil’. We’ll shortly look at a simple way of making sure that errors like this don’t happen again..
MESSAGES, METHODS AND POLYMORPHISM
This example, incidentally, is based on a classic Smalltalk demo program which illustrates how the same ‘message’ (such as talk) can be sent to different objects (such as cats and dogs), and each different object responds differently to the same message with its own special method (here the talk method). The ability to have different classes containing methods with the same name goes by the fancy Object Orientated name of ‘polymorphism’ – a term which, once remembered, can safely be forgotten...
When you run a program such as 6dogs.rb, the code is executed in sequence. The code of the classes themselves is not executed until instances of those classes (i.e. objects) are created by the code at the bottom of the program. You will see that I frequently mix class definitions with ‘free standing’ bits of code which executes when the program is run. This may not be the way you would want to write a major application but for just ‘trying things out’ it is extremely convenient.