So there’s a lot of options out there for debugging, but a lot of people
miss the simplest one, and that’s
p is a tool for inspecting the
contents of objects and outputting them to the standard output. This
article goes into how to use
p, when to use
p, and how
p works (so
you can make it work with your own stuff!).
p is frequently equal to or better than most of your silly
When Do I Use
Anytime you do not know what’s happening to your objects.
- Method call on the fritz? Use
pon the receiver. Maybe you’re working with a different object that’s a duck facsimile, behaving similarly but not completely the same!
- Don’t know what’s in that string causing the encoding error? Use
pto see the literal byte stream escaped in all its octal glory.
- Want to see the instance variables on your ActiveRecord models? Rails
supports this (and we’ll see how in a bit) with
How Do I Use
Simple! You just supply
p before your desired result to inspect:
1 2 3 4 5 6 7 8
How Does It Work?
A little call called Object#inspect is used to return the basic representation which we can see with the “Object” line in the previous code block.
You can call it directly to get a string of the literal implementation.
p is actually implemented something like this:
1 2 3 4 5
You can define this in your own classes!
1 2 3 4 5 6 7 8
Pretty neat, huh? Speaking of pretty…
What If I Have a Big-Assed Array and/or Hash and Want to Get a Pretty-Printed Version?
Now, folks, that is a heading.
Anyhow, there is another call, just as simple! It’s called
pp and its
inspect analogue is called
pretty_inspect. However, it is not built
into ruby directly, but it is in the standard library:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17