One step forward while ‘pry’ing into Ruby code

Jason Arnold
3 min readSep 15, 2016

--

I’ve recently been accepted to a coding bootcamp and along with that have started on some of the prework (the work you do before you show up the first day) that has been assigned to me. The majority of this prework is based on Ruby. Ruby has its own interactive shell environment baked-in called ‘IRB’ (Interactive Ruby Shell)(why not IRS, then?… too many negative feelings about taxes I suppose).

With IRB you can drop into a Ruby-aware terminal environment and test code. BASH doesn’t work in IRB and vice-versa. Totally separate things. For basic troubleshooting or testing, this is fine. Pop in, do your thing, pop out again. No big deal.

Basic Ruby goodness in IRB

All well and good if you don’t need anything too fancy. What if you have a method that isn’t working as expected and would like to be able to see what is going on while it is running. You think you know what those variables are inside that method, but do you? Do you really?

This is where Pry can help. Pry is an alternative to IRB and can also give you eyes into your code by ‘prying’ it open and seeing what is going on while it is running.

To start using Pry you need three things. 1. Install the pry gem. 2. Add the “require ‘pry’” line to the top of your Ruby file. 3. Add the ‘binding.pry’ line to the location in your script where you want it to stop and open it in Pry.

Here is an example of a basic method being run and prying into it.

Using pry to stop the method and see what the value of that variable really is.

What if you have a method that is a bit more complicated? Maybe something with a loop or an .each call? That was an issue I ran into during my prework and wasn’t sure how to get around it at first. The problem was that pry was stopping the loop during its first iteration but I needed to investigate what was going on in the last iteration. How to do this? Luckily, Pry has a good help file which is where I found the ‘continue’ command.

Let’s see that in action. Here’s a new method that is iterating through an array.

Looking at the first iteration through an array.

If I was having a problem with using puts for that first item in the array, then I’m done. I can see what the issue is, fix it, and move on. But what if I want to see an issue with the next item or the last one? I need to step through the .each loop. This can be done with ‘Ctrl-D’.

Now on the second iteration of the array.

As you can see, the ‘word’ variable is now set to “what” which is the second item in the array. You can keep using the ‘Ctrl-D’ command to get through each step of the array. When there are no more iterations, Pry will simply exit the loop and go back to the terminal prompt. If you want to exit Pry early, you can use the ‘!!!’ command.

--

--