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 because it’s often loaded into just the development and test groups in the Gemfile, it’s not available on staging or production. That sounds great until we accidentally leave an ap statement in the code, and it goes to staging and causes a 500 error. With the other methods, which are core Ruby, the worst that happens is STDOUT spew.

Here’s a comparison from a Rails 6 console comparison in Ruby 2.4.1 with awesome_print in the Gemfile. This comparison uses a couple of collections, a hash with an array value, and a plain array. This output is lightly edited from a Rails console session:

Get hands-on with 1400+ tech skills courses.