prosseek
prosseek

Reputation: 191159

Ruby's to_s method question (from Axe book 2nd edition)

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]

Upvotes: 1

Views: 1368

Answers (5)

mikej
mikej

Reputation: 66343

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

Upvotes: 3

Paige Ruten
Paige Ruten

Reputation: 176803

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"

Upvotes: 2

bensie
bensie

Reputation: 5403

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

song = Song.new
puts song.to_s

Upvotes: 1

bennybdbc
bennybdbc

Reputation: 1425

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

Upvotes: 0

Justin Ethier
Justin Ethier

Reputation: 134255

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.

Upvotes: 0

Related Questions