Debugging with Pry
One of the first things that I think anyone wanting to learn to code should do is learn about how to debug your code. For Ruby, there are a few options, but the one that I'm most familiar with is pry.
So, what is Pry? Pry is a Ruby gem. You can install it in Ruby by typing the command
So, what is Pry? Pry is a Ruby gem. You can install it in Ruby by typing the command
gem install pry
This installs the most current version of pry. Now you just have to require it in your files. You can do that by typing require 'pry' and adding it to your gemfile.
Now lets move on to how to use it. When you want to figure out what's going wrong in your code, you type: binding.pry in your code. The code in the method that you place the binding.pry will execute and any code below that will not. Here's an example.
Here, pry will stop your code from executing right before it gets to line 22.
That means that you can find the value of car and @@all. If there were additional code below that line, it wouldn't execute, unless you put it into the pry console.
Here is why this is useful. You can test code without changing your current code. Meaning, if I wanted to see what would happen if I changed the value or tested out other code entirely, you can do that in pry without it changing what you currently have written.
One thing to remember... If there are variables after your binding.pry, you won't have access to their values.
Since my code stopped excuting before updated_car, pry won't know the value. What you can do to get around this, is copy and paste the code into the pry terminal.
Like this:
This a great technique for determining why your code isn't working. Often times, it's because the value of a variable is not what you expect.
Helpful hints:
If you are in a loop and type exit it will exit the loop only once.
f you want to exit the loop completely, type exit! If you aren't in a loop, just type exit and you won't be in the pry console anymore.
Here's a list of pry commands that you may find useful.
Pry Commands Cheat Sheet
Pry Commands Cheat Sheet
I hope that you get a lot of use out of Pry, now knowing how you can use it. It's a fantastic tool for debugging your code!
Comments
Post a Comment