tags:

views:

94

answers:

5

According to the axe book (2nd edition), we can use to_s as follows.

class Song
  def to_s
    "Song"
  end
end

song = Song.new()
song.to_s

But, it doesn't give me anything, in order to print something to the stdout, I should run

  def to_s
    p "Song"  
  end

Is there any change since the ruby 1.8.2 when the book was written for? My ruby version info is 1.8.7 for Mac.

ruby 1.8.7 (2009-06-08 patchlevel 173) [universal-darwin10.0]

A: 

Right, to_s has always just converted the object to a string. It is up to your program to then use that string - for example, by writing it to stdout.

Justin Ethier
A: 

This is because the above method simply returns "song", it doesn't print it. Your program should do the printing itself.

bennybdbc
+1  A: 

In your case you would want your last lines to be:

song = Song.new
puts song.to_s
bensie
+2  A: 

That example might be meant to be typed into a REPL like irb, which would look like this:

irb> class Song
  ..   def to_s
  ..     "Song"
  ..   end
  .. end
  => nil
irb> song = Song.new()
  => Song
irb> song.to_s
  => "Song"
yjerem
+2  A: 
mikej