I copied the following Ruby code from the Internet and made a few changes.
#insert code here
But it doesn't work!
Please help. What can I do to debug the program by myself?
I copied the following Ruby code from the Internet and made a few changes.
#insert code here
But it doesn't work!
Please help. What can I do to debug the program by myself?
There is many debuggers with different features, based on which you make choice. My priorities was satisfied with pry-moves which was:
Print out the variables whenever possible. (This is called printf debugging) You can do this by running
or
If you want to make this easier to type, then you may want to use the exemplor gem.
Turn warnings on. If you're running
ruby
then run it with the-w
switch (egruby -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 misspell an instance variable, once warnings are on you'll getUnderstand the concept of a binary chop (the following quote is from Practices of an Agile Developer)
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
gives a value of
false
, even though you'd think it'd returntrue
. In that case, you may want to look at the documentation. Web sites for documentation include ruby-doc.org, or APIdock. In the latter case, you'd typeinclude?
next to the magnifying glass near the top right corner, choose theinclude?
which hasArray
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.
In Ruby:
then,
b <line>
: put break-pointn(ext)
ors(tep)
andc(ontinue)
p(uts)
for display(like perl debug)
In Rails: Launch the server with
and add
debugger
in the code.-w
(warnings) flagIf you are using RubyMine, debugging ruby scripts is simple and straightforward.
Suppose you have a Ruby script hello_world.rb
1. Set breakpoints
Set a breakpoint at line 6 as below.
2. Start debugging
Now you can just start the debugger to run the script:
3. Inspect variables, etc.
Then when the execution hits a breakpoint, you'll be able to inspect variables, etc.
Further information for your reference