Thanks. The child is behaving at last ;)

I think that I'll be grabbing a new book once I find one with slightly
clearer descriptions and code base. 

Now I understand that one must declare (if that's the right word), all
of the instance variables in for a child class and any variables that
it will inherit from it's parent. Do the same for the child's method.


On Sat, 21 Jan 2006 10:00:04 +0900 Eero
Saynatkari <ruby-forum-reg / mailinator.com> wrote:

> John Maclean wrote:
> > I'm sorry I still don't get it. (To be honest I think that I can
> > narrow down this problem to the book not having all of the code in a
> > single place)...
> > 
> > I can understand that for example (p27) is telling us that there's a
> > "right way" and "wrong way" to specify methods for child instances..
> > so what's wrong with this?
> > 
> > #!/usr/bin/env ruby
> > require 'class_Song.rb'
> > 
> > # test if this class has been loaded correctly
> > Object.const_defined?(:Song)
> > 
> > class KaraokeSong < Song
> >   # grab all the properties from the parent but add another instance
> > variable
> >   def initialize(lyrics)
> >     @lyrics = lyrics
> >   end
> > 
> >   def to_s
> >     super + " [#@lyrics]"
> >   end
> > end
> > 
> > song = KaraokeSong.new("And now, the...")
> > #song = KaraokeSong.new("My Way", "Sinatra", 225, "And now, the...")
> 
> There is no #initialize method that takes four parameters
> at this point (see below).
> 
> > song.inspect
> > song.to_s
> > puts song
> > 
> > The above has not specified a name, artist and duration - but that's
> >  coming from the parent class, is it not?
> 
> All you are getting from the parent class are the actual
> variables and an #initialize method that takes three parameters.
> In your child class, you define a new #initialize that only takes
> one parameter (overriding the one from the parent class) so that
> all KaraokeSong.new can see is the one with just one parameter.
> 
> Even if the child class had a method looking like this:
> 
>   def initialize(lyrics)
>     super
>     @lyrics = lyrics
>   end
> 
> The problem would still be that the method itself does not
> take more than one parameter and you would see an error if
> you tried to pass it four. So the correct way indeed is to
> have your child class with an #initialize that takes all
> four parameters and then call #super with the three parameters
> that must go to the parent- (or super-) class.
> 
> > < Warning messages elided />
> 
> 
> E
> 


-- 
John Maclean
MSc (DIC)
07739 171 531