scribble

Holistic Engineering

E-Mail GitHub Twitter

17 Jun 2012
The Best Ruby Debugger: Kernel.p!

So there’s a lot of options out there for debugging, but a lot of people miss the simplest one, and that’s p. 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!).

In short, p is frequently equal to or better than most of your silly debuggers.

When Do I Use p?

Anytime you do not know what’s happening to your objects.

  • Method call on the fritz? Use p on 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 p to 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 p!

How Do I Use p?

Simple! You just supply p before your desired result to inspect:

p obj
# outputs "#<Object:0x007fcce3848cc8>"
p obj.method # return value!
# same
p "here's a literal string"
# outputs "here's a literal string" (including the quotes)
p 1
# 1 (yes, that's what it outputs)

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:

module Kernel
  def self.p(obj)
    puts obj.inspect
  end
end

You can define this in your own classes!

For example:

class Foo
  def inspect
    "#{self.object_id} - this is pretty awesome, aye"
  end
end

f = Foo.new
p f # outputs: "123123123 - this is pretty awesome, aye"

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:

require 'pp' # this is important!

p %w[one two three]

# [ "one", "two", "three" ]

pp %w[one two three]

# [
#  "one",
#  "two",
#  "three"
# ]

pp (1..300).to_a

# 302 lines of complete awesome, and too much to print here.

Happy Debugging!


Til next time,
Erik Hollensbe at 03:04

scribble

E-Mail GitHub Twitter