I did do some searching, but can\'t find an answer to simple question.
What is difference between p
and pp
in Ruby? I know you need to
They differ slightly.
data = [false, 42, %w{fourty two}, {:now => Time.now, :class => Time.now.class, :distance => 42e42}]
p data
[false, 42, ["fourty", "two"], {:now=>2012-01-25 19:23:06 +0000, :class=>Time, :distance=>4.2e+43}]
pp data
[false,
42,
["fourty", "two"],
{:now=>2012-01-25 19:23:06 +0000, :class=>Time, :distance=>4.2e+43}]
Please note: I stole the test data from a site showing the difference between pp and their gem.
p
prints a String representation of an object, followed by a newline. So does puts
. The difference is that puts
uses to_s
to convert the argument to a String, and p
uses inspect
. This means p
is often more useful for debugging than puts
.
pp
is "pretty print"; it uses pretty_inspect
to obtain a String representation of an object.
p
is used to inspect a variable as a debug aide. It works printing the output of the method #inspect
. For example p foo
will output the content of foo.inspect
.
Sometimes you need to debug complex variables or nested variables. In this case p
will output a long line that is hard to understand. Instead, pp
will put try to arrange the content of the variable so that it is easier to understand, for example indenting nested arrays or using one line for each instance variable of a complex object. pp
does this calling the #pretty_inspect
method (the pp
library adds #pretty_inspect
methods to many classes such as String
, Array
or Struct
).
To remember: p
= print, pp
= pretty print.