Pretty-Printer for Ruby Objects (pp)
As I mentioned before, Ruby standard libraries run the gamut from extreme simplicity to deep complexity. I figured we’d kick things off with something in the former category.
If you’re reading this book, you’ve certainly made use of Kernel#p during debugging. This handy method,
which calls #inspect on an object and
then prints out its result, is invaluable for basic debugging needs.
However, reading its output for even relatively modest objects can be
daunting:
friends = [ { first_name: "Emily", last_name: "Laskin" },
{ first_name: "Nick", last_name: "Mauro" },
{ first_name: "Mark", last_name: "Maxwell" } ]
me = { first_name: "Gregory", last_name: "Brown", friends: friends }
p me # Outputs:
{:first_name=>"Gregory", :last_name=>"Brown", :friends=>[{:first_name=>"Emily",
:last_name=>"Laskin"}, {:first_name=>"Nick", :last_name=>"Mauro"}, {:first_name=
>"Mark", :last_name=>"Maxwell"}]}We don’t typically write our code this way, because the structure of
our objects actually means something to us. Luckily, the
pp standard library understands this and provides
much nicer human-readable output. The changes to use pp instead of p are fairly simple:
require "pp" friends = [ { first_name: "Emily", last_name: "Laskin" }, { first_name: "Nick", last_name: "Mauro" }, { first_name: "Mark", last_name: "Maxwell" } ] me = { first_name: "Gregory", last_name: "Brown", friends: friends } pp me # Outputs: {:first_name=>"Gregory", :last_name=>"Brown", :friends=> [{:first_name=>"Emily", ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access