p vs puts in Ruby

p foo prints foo.inspect followed by a newline, i.e. it prints the value of inspect instead of to_s, which is more suitable for debugging (because you can e.g. tell the difference between 1, "1" and "2\b1", which you can't when printing without inspect).


p foo is the same as puts foo.inspect


It is also important to note that puts "reacts" to a class that has to_s defined, p does not. For example:

class T
   def initialize(i)
      @i = i
   end
   def to_s
      @i.to_s
   end
end

t = T.new 42
puts t   => 42
p t      => #<T:0xb7ecc8b0 @i=42>

This follows directly from the .inspect call, but is not obvious in practice.

Tags:

Ruby