...

/

The Humble Print Statement

The Humble Print Statement

Learn to interpret debugging messages and how to debug our app with the help of print statements.

Debugging with print statements

My initial troubleshooting tool of choice is a plucky little Ruby method called p, for print. Perhaps we’ve heard of it.

We realize that debugging with the p statement sounds like trying to fix our television by kicking it to many of us. The p method’s defense is dirt-simple, works anywhere, and is infinitely adaptable to our current troubleshooting needs. An elegant weapon for a more civilized age, so to speak.

The p method calls inspect on its argument and then outputs it to STDOUT using Ruby’s even-more-primitive puts. We prefer p to puts because the extra call to inspect generally results in a more readable output. (Though in poking around, it looks like puts does a better job with mixed data these days than it did back in the Ruby 1.8.7 era).

Debugging output

A couple of other methods are particularly good at displaying structured data. Ruby defines the method y, which takes its argument and outputs it to STDOUT in YAML format. This is valuable in direct proportion to our ability to read complicated YAML formats.

Awesome Print

The Awesome Print gem is, well, pretty awesome. It’s available with gem install awesome_print and lots of examples and docs. Including Awesome Print gives us the ap method, which awesomely prints things. Even nicer, we get the logger helper method Rails.logger.ap, which awesomely prints to the Rails log (by default, at the debug level). Awesome Print also has several options to customize the output, but we’ve never used them.

One minor downside to Awesome Print is that ...