I’m trying to learn how to step through Ruby code (written by more experienced programmers) in order to improve my knowledge of Ruby. Problem is that I don’t really know how to do it well. Googling the topic brought me to an about.com page on Ruby; I thought a higher quality more comprehensive answer should belong on StackOverflow, so if anyone can write an answer (with an example) for it, showing how a beginner can step through code to learn as much as possible about it, it’d be much appreciated.
5
What you’re looking for is a debugger. With ruby 1.8, the ruby-debug
gem provides the canonical one, and in ruby 1.9, the debugger
gem provides a version of its successor that is well-maintained.
Start your program with the gem loaded, for example ruby -rdebugger yourfile.rb
, and you’ll have access to the debugger.
The debugger kicks in at a breakpoint, which is a signal to suspend execution, and give you a chance to poke around. Typically, the easiest way to set a breakpoint is to add a source line at the point in execution you’re interested in. Inserting a call to debugger
, does this. Lets debug this function that asks for a user name, but restricts it to doctors. It’s not letting “Dr. Bob” log in:
def get_user
debugger # This is where we break.
name = ""
begin
print "What is your name?: "
name = gets
end until name.match /ADr /
puts "Welcome, #{name}."
name
end
user = get_user
Lets launch it:
ruby -rdebugger login.rb
The program starts executing, then the debugger breaks us at line four. It shows us the next statement which is to be executed next. We can get a more complete listing of our surroundings by typing l
.
(rdb:1) l
[-1, 8] in login.rb
1
2 def get_user
3 debugger
=> 4 name = ""
5 begin
6 print "What is your name?: "
7 name = gets
8 end until name.match /ADr /
You can examine the result of expressions by using the p
command. p name
will show us that the name
variable is an empty string at this point of execution.
n
steps, which executes the next line, and returns control to the debugger. s
will allow you to step into a method call. c
continues execution until the program terminates, or hits another breakpoint. In this case, we’d probably want to use the n
command to trace the execution of this method. Just these handful of commands describes the vast majority of my debugging sessions.
The debugger has has interactive help which can be accessed with help
. A more conversational tutorial on the web is: Debugging with ruby-debug