From: Eero Saynatkari Date: 2006-01-21T10:00:04+09:00 Subject: Re: Basic Inheritance questions {noob alert:- pickaxe ed. 2, 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 -- Posted via http://www.ruby-forum.com/.