puts e p in Ruby

Asked

Viewed 98 times

4

What’s the difference between p and puts in Ruby?

When I should choose to wear one or the other?

1 answer

7


The two show different representations of a given object in the application’s standard output. The puts shows the most standard human readable representation by calling the method to_s, as long as the p makes the call of the method inspect which is more geared towards debug.

TL;DR;

p

Make the call of the method inspect and type the output in the default output. For example: p foo the exit will be the return of foo.inspect.

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

Code example:

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

@foo = Foo.new
p @foo

The way out will be something like:

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

puts

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

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

puts @foo

It’ll be something like:

#<Foo:0x0055da22ac5c40> 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.