Happy holiday for all!
I have two classes (most of them copied from Pickaxe
2)and they work fine. But I get the address for
each object if I comment out method Song#to_s. How to
explain them?
Thanks,
Li
class Song
def initialize(name,artist,duration)
@name=name
@artist=artist
@duration=duration
end
attr_reader :name, :artist, :duration
def to_s
“#@name\t#@artist\t#@duration”
end
end
class Songlist
def initialize
@songs=Array.new
end
def append(song)
@songs.push(song)
#self
end
def all_songs
@songs.each{|song| song}
end
end
populate the Songlist from a file
list=Songlist.new
File.open(‘song.txt’).each_line do |line|
if line=~/\w+/ #skip empty line
name,artist,duration=line.split(’,’)
s=Song.new(name,artist,duration)
list.append(s)
end
end
puts" list all songs"
puts list.all_songs
puts
define Song#to_s and the screen output
ist all songs
song1 author1 20
song8 author1 4
song5 author2 6
song7 author1 8
song2 author5 1
song4 author7 3
song6 author3 5
song8 author6 7
###comment out Song#to_s and the screen output
list all songs
#Song:0x28ab39c
#Song:0x28ab144
#Song:0x28ab090
#Song:0x28aade8
#Song:0x28aac44
#Song:0x28aaa8c
#Song:0x28aa9b0
#Song:0x28aa514