With and without Song#to_s

C

chen li

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>





__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail.yahoo.com
 
T

Timothy Hunter

chen said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top