Is there any difference between p and puts in Ruby?
+11
A:
p foo does puts foo.inspect, 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).
sepp2k
2009-08-10 14:52:05
Yep, p (and puts) are both in the Kernel module so you can see the details here: http://www.ruby-doc.org/core/classes/Kernel.html#M005961
mikej
2009-08-10 14:54:50
+3
A:
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.
ezpz
2009-08-10 14:59:22