Debugging your code with Pry.

Joel Diaz
2 min readJun 14, 2021

I just finished the third module of the software engineering program at Flatiron School, which is about Ruby, and they introduced me to a tool named Pry.

What is Pry?

Pry is a debugging tool that Ruby developers use to debug their code.

Pry stops your code at a specific line to help programmers evaluate their code and see what needs to be fixed without changing their actual code. Because Pry is a Ruby gem, your programs must require 'pry'then want to add binding.pry to a specific line when you want to stop your code.

How does Pry work?

In the example below, we created a method where we set x to a value of 3, y to a value of 5, and z to the sum of x and y.

require 'pry'def example  x = 3  y = 5  binding.pry  z = x + y  binding.pry  puts zendexample

Running this code will return this in your terminal:

4: def example
5:
6: x = 3
7: y = 5
=> 8: binding.pry
9: z = x + y
10: binding.pry
11: puts z
12:
13: end
[1] pry(main)>

What this means is that pry stopped our code from running on line 7, so everything after line 7 has not run yet.

Since our code stopped at line 7, we can see get the values of x and y and even play around with such values:

[1] pry(main)> x
=> 3
[2] pry(main)> y
=> 5
[3] pry(main)> y - x
=> 2

However, because our code has not yet get past line 8 we can not see the value of z

[4] pry(main)> z
=> nil
[5] pry(main)>

Typing exit on the terminal will make our code run again:

4: def example
5:
6: x = 3
7: y = 5
8: binding.pry
9: z = x + y
=> 10: binding.pry
11: puts z
12:
13: end
[1] pry(main)>

Notice how now our code stopped at line 10. If we enter z again we get:

[1] pry(main)> z
=> 8
[2] pry(main)>

Pry allows us to play around with our code without actually change it, for example, let's say we wanted z to be equal to 500, we can change the values of x, y, and z and manipulate them until we know which numbers to add to get 500 and then change put them into our code.

--

--