1

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]

prosseek
  • 182,215
  • 215
  • 566
  • 871

5 Answers5

3

The Pickaxe book uses a common notation of e.g.

song.to_s"Song: My Way--Sinatra (225)"

to indicate that "Song: My Way--Sinatra (225)" is the value of the expression on the left. However it isn't printed out unless you explictly use a puts.

An appropriate implementation of to_s on an object will return a string representation of that object (e.g. the name for a person or the title and ID for a blog post) but won't actually have any side effects itself (such as outputting something.)

If you use irb, the interactive Ruby interpreter it prints out the value of each expression for you without an explicit puts. e.g.

$ irb
irb(main):001:0> 2 + 2
=> 4
mikej
  • 65,295
  • 17
  • 152
  • 131
2

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"
Paige Ruten
  • 172,675
  • 36
  • 177
  • 197
1

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

song = Song.new
puts song.to_s
bensie
  • 5,373
  • 1
  • 31
  • 34
0

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
  • 131,333
  • 52
  • 229
  • 284
0

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

bennybdbc
  • 1,425
  • 3
  • 15
  • 24