Debugging for Dummies
Unfortunately, “pest control” is part of the job description. Wether you like it or not. THERE. WILL. BE. BUGS. They’re like these pesky vile little creatures that can be difficult to get rid of and when you do, before you know it, there goes another one. It can be a very daunting experience to deal with. Luckily! With the right tools anyone can exterminate them with ease. Enter Raid.
Uhhh. . . I mean, Pry.😬
Pry is a powerful tool that Ruby developers can use to debug programs. Debugging is something that all programmers do throughout their careers. We spend a ridiculous amount of time debugging. So it occurred to me that getting better at it can improve work flow and efficiency. With that being said let’s get into it!
First things first. Installation!
You’ll need to install the gem by adding it to your Gemfile and running a bundle install in your terminal.
Or, you can manually install it: gem install pry.
Require it at the top of the file you are working in with ‘require pry’ and you’re all set.
Now let’s take a look at the code below.
What this will do is ask the user to guess a number. It will then compare the number the user guessed to the random number and output a message based on the condition.
Let’s run our file and get started!
Oh but look! there’s a bug!
No worries. Let’s bind pry right before the if block that is causing the error like so. . .
This allows you to pause execution at any given line of code, allowing you to check how everything is working.
Then we’ll run the file, and you should see something like the following:
Now what we can do is test what we’d expect our values to be. Keep in mind, that if there are variables after your binding.pry, you won’t have access to their values. If you type user_input in the terminal, it’ll show you the number the user guessed. Then if you type random_number, it’ll show you the random number generated.
This is excellent for figuring out why your code isn’t working. Often times, it’s because the value of a variable is not what you expect. The problem here is that the less than (<) or greater than (>) comparison operators throw an error when the data types are different. It can’t determine wether a number is less than or greater than a string. To fix this we’ll go ahead and convert the users input into an integer.
Type exit to quit pry, run the file (don’t forget to save!) and test your assumptions again and you should see that the user input is now a number and not a string.
Remove the binding and run the file yet again and it should be bug free!
Pry is absolutely awesome and I encourage that any Rubyist learns to use it well. There is so much more Pry is capable of. This was just the basics!
I’ll admit, I was guilty of solely relying on puts statements to debug my code and I personally feel it’s not very effective. Don’t be a puts debugger but instead a pry debugger. You won’t regret it!