1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Debugging Ruby

Fixing Program Problems


Debugging a program means to find the source of a bug or problem and fix it. Though the concept is straightforward, the process isn't always as clear-cut, especially when there are multiple levels of abstraction. For quick tests, it's common to put puts statements in various places throughout your program to check the value of a variable as it progresses. However common, though, this practice is limited and error-prone. These puts statements can often be left behind, producing unwanted output in code paths that are not always followed during the tests.

The Ruby Debugger

Most languages have a debugger and Ruby is no exception. A debugger is a program you can use to run your Ruby programs, stop them at arbitrary places and do things like examine the value of any variable, look at the call stack and change the values of variables. Ruby comes with a debugger so, when running your program, you simply need to require the 'debug' library from the command-line with -rdebug.

In this example program, a number of lines are read from the file listed in ARGV[0]. The lines are comma-separated values, basically a simple number table. The program reads each line, divides the first number by the second and then stores it in the third number. It then prints out each line re-joined by commas.

There is, however, a problem. Another program that uses this output data is crashing. It seems some of the numbers it's loading from the third column (the column the Ruby program has written) are invalid. Assuming the datasets are very large, finding exactly which number is incorrectly generated may be difficult.

#!/usr/bin/env ruby

lines = File.readlines(ARGV[0])

lines.each do|l|
nums = l.split /,/
nums.map!{|n| n.to_f }

nums[2] = nums[0].to_f / nums[1].to_f

puts nums.join(',')
  1. About.com
  2. Technology
  3. Ruby
  4. Advanced Ruby
  5. Debugging Ruby

©2014 About.com. All rights reserved.