From: Dave Thomas Date: 2000-12-20T15:23:57+09:00 Subject: [ruby-talk:7744] Re: New to Ruby takaoueda@my-deja.com writes: > In article , > Dave Thomas wrote: > > Congratulations. > > Thank you Thomas. Now I am at page 39. If I revise > Song.new('title1','artist1',1), etc > to > Song.new('title1', 'artst1',1).to_s, etc A SongList is a list of Songs, rather than a list of strings, so the original is correct. > and use the definition of class Song at page 19 and page 21, then it > works. However, is there any way to rewrite the class Song and leave > the bottom of page 39 intact? The code examples that you are looking at actually execute to generate the output you see in the book, so there shouldn't be any need to rewrite class Song--the code should be correct. Let's look at the complete code for this example: class SongList def initialize @songs = Array.new end def deleteFirst @songs.shift end def deleteLast @songs.pop end def append(aSong) @songs.push(aSong) self end end class Song def initialize(name, artist, duration) @name = name @artist = artist @duration = duration end def to_s "Song: #{@name}--#{@artist} (#{@duration})" end end list = SongList.new list. append(Song.new('title1', 'artist1', 1)). append(Song.new('title2', 'artist2', 2)). append(Song.new('title3', 'artist3', 3)). append(Song.new('title4', 'artist4', 4)) list.deleteFirst list.deleteFirst list.deleteLast list.deleteLast list.deleteLast It runs, but produces no output. In the book, when you see the arrow after a line of Ruby code, that's pointing to the value returned by that line. That value is normally the result of 'inspect'ing the expression. However, this is pretty ugly for classes: if we change the last 5 lines above to use 'p' (which does an inspect): p list.deleteFirst p list.deleteFirst p list.deleteLast p list.deleteLast p list.deleteLast we get # # # # nil which isn't pretty.[1] So for this example, we'll use #puts, which invokes the object's to_s method:[2] puts list.deleteFirst puts list.deleteFirst puts list.deleteLast puts list.deleteLast puts list.deleteLast and we get Song: title1--artist1 (1) Song: title2--artist2 (2) Song: title4--artist4 (4) Song: title3--artist3 (3) nil Just like the book (which is a relief ;-) In this example, we were simply trying to show that the methods in SongList were indeed returning the correct Song objects. I hope this helps. Dave Footnotes: [1] And it made out lines too long [2] How did we do that in the book? We cheated. We overrode #inspect in class Song to call to_s. That's because the preprocessor that generates the typeset code fragments always uses #inspect to get the value, so we had to change the input slightly to fool it.