Debugging Using a Console Debugger
Learn to debug a program using a console debugger.
We'll cover the following...
pry
We’re already familiar with pry, which is another read-execute-print-loop (REPL). pry implements more features than irb (Interactive Ruby, standard REPL). With a little bit of extra effort, we can use pry as a console debugger. Let’s look into the basics of debugging with pry. Knowing how to use this tool will save us a lot of time.
If pry is not installed on our system for any reason (we can check it with which pry), we can type a simple installation command:
$ gem install pry pry-doc
This command installs two gems: pry and pry-doc. The latter is a plugin for pry (normally, plugin names for pry start with the pry- prefix) and contains documentation about native Ruby methods.
We can type pry commands once pry is executed by just typing in our terminal, for example:
$ pry
> help
Try the above command in the following terminal.
We can get help for any command from the list above by adding -h, for example:
[1] pry(main)> whereami -h
Usage: whereami [-qn] [LINES]
...
We will describe our current location. If we use binding.pry inside a method, whereami will print out the source for it.
Program to square a number
Let’s look at the Ruby program that raises a number to the second power. So, for 2 the result is 4, for 3 it is 9, for 4 it is 16, etc…This operation equals to multiplying a number by itself one time:
# Program for raising a number to the second powerdef random_powpow(rand(1..10))enddef pow(x)x ^ 2endputs random_pow
Can we spot anything wrong above? ...