With and without Song#to_s

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

chen li wrote:

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?

T
puts calls to_s on each object that it writes. If you don’t supply a
to_s method for your class then the to_s method in your class’s
superclass will be used. Since the superclass is Object, the Object#to_s
method is used. This version of to_s simply formats the object’s class
and its id as a string.

ri Object#to_s for more information.

— Timothy H. [email protected] wrote:

ri Object#to_s for more information.

What I don’t understand is that I don’t call Song#to_s
in my script why does it affect my codes?

Thanks,

Li

chen li wrote:

and its id as a string.

ri Object#to_s for more information.

What I don’t understand is that I don’t call Song#to_s
in my script why does it affect my codes?

puts calls to_s