What is difference between “p” and “pp”?

后端 未结 3 1782
既然无缘
既然无缘 2020-12-16 10:21

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

相关标签:
3条回答
  • 2020-12-16 11:00

    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.

    0 讨论(0)
  • 2020-12-16 11:16

    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.

    0 讨论(0)
  • 2020-12-16 11:20

    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.

    0 讨论(0)
提交回复
热议问题