Adam Gotterer
Adam Gotterer

Reputation: 638

Why does calling "p" on a Ruby object call to_s and then output a non string?

I'm curious why when you call "p" on an object why it calls the .to_s method but doesn't actually return a String. When you explicitly called .to_s it clearly outputs as a string.

1.9.3p194 :078 >   class Test
1.9.3p194 :079?>     def to_s
1.9.3p194 :080?>       puts 'to string called' 
1.9.3p194 :081?>       "testing"
1.9.3p194 :082?>     end
1.9.3p194 :083?>   end
 => nil 
1.9.3p194 :084 > x = Test.new
to string called
 => testing 
1.9.3p194 :085 > x
to string called
 => testing 
1.9.3p194 :086 > p x
to string called
testing
to string called
 => testing 
1.9.3p194 :087 > p x.to_s
to string called
"testing"
 => "testing" 

Upvotes: 1

Views: 159

Answers (1)

Paul Rubel
Paul Rubel

Reputation: 27252

p writes a stingified representation of the passsed in object to standard out. It then returns itself. If you want the string value that p prints you can use the inspect method:

> a = p 233
233
> a.class # Fixnum
> 233.inspect # "233"

Upvotes: 4

Related Questions