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.