Pry, Oh Pry: the IRB Alternative

Ben Yellin
3 min readFeb 7, 2019

--

Why Pry?

Ruby comes with the built-in console/REPL irb, so why use pry? From a high-level, Pry improves the user-experience with features like enhanced tab-completion, syntax-highlighting, and user customization. But it’s the advanced commands and plugins where it really shines.

Pry Commands

Pry comes with a large collections of useful commands to aide in debugging. They’re all ruby methods but intended to be used as if it was a command-line (e.g. command -h). Running the command helpwill list everything available, along with descriptions.

_

_represents the result of the last command run in pry. Useful for saving variables after the fact:

> Person.find(1)

> p = _

cd/ls

Pry introduces the idea of navigating the classes/objects (“scopes”) of your ruby program as if they were directories in the terminal:

> cd Person.first   # cd into a class instance
> cd Person # and classes themselve
> cd .. # go up one level
> cd / # go to ‘root’ (where pry session started)
> cd - # switch between two scopes
> gem-list # list available gems
> gem-cd # cd into gem

And just as in a terminal, you can list contents with the command ls:

> ls -m          # Methods
> ls -M # Instance Methods
> ls -g # Globals
> ls -l # Local Vars
> ls -i # Instance Vars
> ls -c # Constants
> ls -G xx # Grep (Search/Filter)> ls -q # Quiet (No Superclass Methods/Vars)> ls -qM -G name # Search for instance methods with 'name'

find-method/show-method/edit

find-methodsearches for a class/module that implements a method.
show-doc displays a method’s built-in documentation, if provided.
show-methodreveals a methods source code.
editmodifies a method/class inside Pry, allowing you to test a change or bugfix without having to restart or reload your console session.

show-model(s)/show-routes/find-route (pry-rails)

The plugin pry-rails switches rails console to use a Pry interface and provides additional commands:

> show-models
Person
id: integer
name: string
> show-routes
person POST /people(.:format) people#create
new_person GET /people/new(.:format) people#new

Don’t want to include pry-railsin your Gemfile? Launch a pry session with your rails environment by running:

pry -r ./config/environment

pry-byebug

The plugin pry-byebug adds support for the advanced debugging gem byebug. This allows for breakpoints, step-by-step debugging, and viewing callstacks.

pry-rescue

pry-rescue is a plugin that automatically opens a pry session whenever an exception is encountered (such as from a failed rspec test).

awesome_print

awesome_print is a gem that pretty prints objects (arrays, hashes, classes, models, etc) in the console for easier readability. Supports Pry, but works in irb or any log output.

--

--