bastibe bastibe - 4 months ago 28
Ruby Question

How to debug ruby code?

I run Ubuntu 10.10. I just want to debug a simple script. After spending half a day trying to figure out how that could be done I give up. What the heck am I supposed to do?

I installed

ruby-dev
from the Ubuntu repository

I ran
sudo gem install ruby-debug
and
sudo gem install ruby-debug-ide


I tried a few different ways to make this work. I tried
require 'ruby-debug'
and then setting
debugger
somewhere in the code. But Ruby won't find
ruby-debug
.

I tried setting up
vim-ruby-debugger
, which will take ages to execute
:Rdebugger myScript.rb
and will allow me to set breakpoints, but there doesn't seem to be a way to execute my code using that debugger.

And I tried to use NetBeans which simply crashed every time I set up the project and clicked anything.

So, dear community: There must be a way to debug Ruby. Not Rails. Nothing fancy. Just some CLI script. Please help me or I lose what is left of my sanity.

Edit:
the gem exec dir was not in my path. So, at least rdebug seems to work now.

Answer

Ruby-debug is for 1.8+ and ruby-debug19 is for 1.9+.

ruby-debug is easy to learn and very useful. You can tell the application to run until a certain condition exists, then have it break, making it easy to locate nil values, or other conditions that occur sporadically.

From the command-line use rdebug appname and you'll end up at the debugger prompt. If you want to run to line 100 and stop you can enter c 100 and the debugger will set a temporary break-point, the program will run then stop there if it's in the execution path. Once it stops the temporary break-point will be cleared. If you always want to stop at line 100 you could do b 100 then c and the debugger will set a permanent break-point, continue, then stop when the break-point is reached. You can clear the breakpoints, set conditional ones that occur when certain conditions apply, etc. You can type n to step to the next instruction skipping over subroutine calls, or s to step into them. There are commands to display contents of variables in various ways, so read through the docs.

From inside rdebug you can drop into an IRB shell with your variables already populated so you can poke at things to see what happens. From inside either you can inspect or set values, helping with what-if adjustments. If you do that from within rdebug you can continue the program with the altered value(s) and see how it behaves.

IRB has its place, and it's great for trying things, but it's not a substitute for the debugger, just as the debugger can do some IRB-ish things, but won't replace it. Both tools are a good combination and beat the heck out of relying on print statements or dumping to a log file.


Pry has emerged as a great combination of IRB and a debugger, and is well worth investigating.