tags:

views:

84

answers:

3

Hi Stack Overflow,

Ruby n00b here. I copied the following ruby code from the internets and made a few changes.

#insert teh codes here

But it doesn't work!

Please help. What can I do to debug the program by myself?

Thanks in advance,

Andrew Grimm

+3  A: 

1) Print out the variables whenever possible. (This is called printf debugging) You can do this by running

STDERR.puts x.inspect

or

STDERR.puts "Variable x is #{x.inspect}"

If you want to make this easier to type, then you may want to use the exemplor gem.

2) Turn warnings on. If you're running ruby then run it with the -w switch (eg ruby -w script.rb). If you're running it from irb, and you're using a version of ruby prior to 1.9.2, type $VERBOSE = true at the start of your session. If you mis-spell an instance variable, once warnings are on you'll get

warning: instance variable @valeus not initialized

3) Understand the concept of a binary chop (the following quote is from Practices of an Agile Developer)

Divide the problem space in half, and see which half contains the problem. Then divide that half in half again, and repeat.

4) If you're successful with a binary chop, you may find that there's a single line that doesn't do what you expect it to do. For example

[1, 2, 3].include?([1,2])

gives a value of false, even though you'd think it'd return true. In that case, you may want to look at the documentation. You may want to look at ruby-doc.org, or APIdock. In the latter case, you'd type include? next to the magnifying glass near the top right corner, choose the include? which has Array underneath it (if you don't know what class [1, 2, 3] is, type [1, 2, 3].class in irb), and you get to include? (Array), which describes what it does.

However, if the documentation doesn't help, you're more likely to get a good answer if you can ask a question on how a specific line isn't doing what it should, rather than why an entire script isn't doing what it should.

Andrew Grimm
Nice answer to your own question.
Bob Jarvis
@Bob Jarvis: I wrote this question in response to [this question](http://stackoverflow.com/questions/3942032/why-does-this-string-comparison-give-that-result-in-ruby/3955609#3955609), where the person could do a little more debugging themselves.
Andrew Grimm
+1  A: 
  1. You can print your variables out along the way
  2. Turn on the -w (warnings) flag
  3. Use a tool such as ruby-debug
ghostdog74
I'll add that `irb` is a great starting place. Try using irb with small questionable chunks. I love ruby-debug (ruby-debug19 for Ruby 1.9+) because it makes it easy to stop the running program, examine variables, drop into irb, then continue running.
Greg
+1  A: 

a) in ruby :

ruby -rdebug myscript.rb then , b : put break-point and n(ext) or s(tep) and c(ontinu) p(uts) for display.

(like perl debug)

b) in Rails

Lauch the server with script/server --debugger and add 'debugger' in the code.

germanlinux