To debug Ruby code, you will need two gems: pry and pry-byebug.
Here is a simple Ruby script that adds up two numbers and prints their sum. Notice the binding.pry
statement at the bottom. This statement adds a breakpoint and tells Ruby to stop execution at that point. At this point, we can examine the current state, step in and out of methods, and exit or continue the execution.
require "pry"
require "pry-byebug"
class Sandbox
def add(a, b)
sum = a + b
sum
end
end
puts "Welcome to the Sandbox"
binding.pry
box = Sandbox.new
sum = box.add(3, 4)
puts "Sum = #{sum}"
If you were to run this code in the terminal, you’d see the following code. Pry pauses the program, and the terminal is waiting for your input. Notice the arrow next to the line number, which tells you exactly where the control is.
➜ sandbox (main) ✗ ruby lib/sandbox.rb
Welcome to the Sandbox
From: /../sandbox/lib/sandbox.rb:15 :
10:
11: puts "Welcome to the Sandbox"
12:
13: binding.pry
14:
=> 15: box = Sandbox.new
16: sum = box.add(3, 4)
17:
18: puts "Sum = #{sum}"
[1] pry(main)>
Type next
on the terminal to go to the following line.
[1] pry(main)> next
From: /../sandbox/lib/sandbox.rb:16 :
11: puts "Welcome to the Sandbox"
12:
13: binding.pry
14:
15: box = Sandbox.new
=> 16: sum = box.add(3, 4)
17:
18: puts "Sum = #{sum}"
[1] pry(main)>
Type step
into the terminal to step inside the add method. Pry will take you inside the add
method.
[1] pry(main)> step
From: /../sandbox/lib/sandbox.rb:6 Sandbox#add:
5: def add(a, b)
=> 6: sum = a + b
7: sum
8: end
During debugging, you can examine the local variables by typing ls in the terminal or simply typing the variable’s name. For example, typing a
shows the a
variable’s value.
[1] pry(#<Sandbox>)> a
=> 3
Type up
to step out of this method, which takes you up a level in the stack. I do this a lot, especially when I find myself in the framework code while debugging.
[2] pry(#<Sandbox>)> up
From: /Users/akshayk/Dev/ruby/sandbox/lib/sandbox.rb:16 :
11: puts "Welcome to the Sandbox"
12:
13: binding.pry
14:
15: box = Sandbox.new
=> 16: sum = box.add(3, 4)
17:
18: puts "Sum = #{sum}"
To continue the execution until the control hits the next breakpoint, type continue
. Type exit
to exit debugging.
If, at any point in time, you’d like to see where you are, type @
or whereami
, and pry will show you the current breakpoint. You might find this helpful when you are reading the help (by typing help in the terminal while debugging), or have cleared the terminal and want to see where you were in the execution.
That’s pretty much how you debug Ruby code. Hope that helped.
Source: How to Debug Ruby Code