I am a brand new Ruby beginner, and I have what is undoubtedly a
painfully simple newbie question.
I'm starting my learning by using the online "Programming Ruby, HTML
Help Edition (v0.3a)", and I'm having trouble getting one of the
earliest code samples in the "Classes, Objects, and Variables" chapter
to work. Here is my slightly modified version (with line numbers added)
of the tutorial code that I've saved in a file called RubyTutorial.rb:
01 class Song
02 def initialize(name, artist, duration)
03 @name = name
04 @artist = artist
05 @duration = duration
06 end
07 def to_s
08 puts "Song: #{@name}--#{@artist} (#{@duration})"
09 end
10 end
11
12 aSong = Song.new("My Way", "Sinatra", 225)
13 print "aSong.to_s ==> "
14 aSong.to_s
15
16 class KaraokeSong < Song
17 def initialize(name, artist, duration, lyrics)
18 super(name, artist, duration)
19 @lyrics = lyrics
20 end
21 def to_s
22 super + " [#{@lyrics}]"
23 end
24 end
25
26 kSong = KaraokeSong.new("My Way", "Sinatra", 225, "And now, the...")
27 print "kSong.to_s ==> "
28 kSong.to_s
When I try to run this from the Windows XP Command Prompt I get the
following result:
C:\Documents and Settings\jl2351\My Documents\Ruby_Scripts>ruby
RubyTutorial.rb
aSong.to_s ==> Song: My Way--Sinatra (225)
kSong.to_s ==> Song: My Way--Sinatra (225)
RubyTutorial.rb:22:in `to_s': undefined method `+' for nil:NilClass
(NoMethodError)
from RubyTutorial.rb:28
C:\Documents and Settings\jl2351\My Documents\Ruby_Scripts>
Obviously the "kSong.to_s" call is supposed to be displaying the
additional lyric information. Since I have no clue, can someone tell me
how to correct this? And why is '+' erroring out as an undefined
method? And any other insights into this error that a rank beginner
might find helpful?
Thanks much.
···
--
Posted via http://www.ruby-forum.com/.