puts and p in Ruby

4

What is the difference between p and puts in Ruby?

When should I choose to use one or the other?

    
asked by anonymous 06.06.2017 / 20:22

1 answer

7

The two show different representations of a given object in the standard output of the application. The puts shows the most human-readable representation by calling the to_s method, while p makes the inspect method call that is more for purposes of debug .

TL; DR;

p

Calls the inspect method and writes the result to the standard output. For example: p foo output will be the return of foo.inspect .

It is most useful for debug , because the inspect method, by default, is geared towards this purpose. The default implementation of it is to return a string with the class name and a list of all its instance variables and their respective values ( inspect will also be called for all these variables).

Code sample:

class Foo
  def initialize
    @foo = 1
    @name = "foo"
  end
end

@foo = Foo.new
p @foo

The output will look something like:

#<Foo:0x0055da22ac5c40 @foo=1, @name="foo">

puts

Calls the to_s method. Applying to the above example, puts foo will print the return of foo.to_s .

Taking as a starting point the class Foo defined above, the output of

puts @foo

It will look something like:

#<Foo:0x0055da22ac5c40> 
06.06.2017 / 20:27