49 Days of Ruby: Day 28 - Debugging
Ben Greenberg
Posted on April 24, 2021
Welcome to day 28 of the 49 Days of Ruby! 🎉
No matter what you do in life, things sometimes don't go as you planned. Learning the tools and techniques to manage issues is critical. This is equally true in coding.
Today, we're going to talk about debugging and share some tools that can help you diagnose and solve issues in your Ruby code.
If you recall from an earlier lesson, we discussed the concept of exceptions. An exception is a message from the language trying to guide you in fixing a problem. For example:
> 1 + "1"
# => (irb):1:in `+': String can't be coerced into Integer (TypeError)
In the above example, we tried to add the integer 1 with the string of "1". This is not possible in Ruby. The result is a TypeError
exception. The type of one of these things does not work with the math operator of +
. Which thing is the problem, look at the error closely:
String can't be coerced into Integer
The problem is the string, the value inside the quotation marks.
One powerful tool in your toolkit for debugging is a close reading of exceptions.
What else can help you? Check your assumptions.
Checking your assumptions means don't assume something is what you think it is. Always check your variable values, your return values, etc. when something goes wrong. You can do that by stepping through your code.
Stepping through your code is the action of putting a pause somewhere in your code's execution so you can examine the state of your data at that point.
There are two very popular Ruby gems you can use in this process: byebug and pry. Both of them act in similar ways, so we'll take a look at one for an example.
This example is from the README for byebug:
def index
articles = Article.find_recent
byebug
end
When your code would start running the #index
method, it would immediately encounter the byebug
and pause at that point. It would then offer you a prompt, first showing you where it paused and then the opportunity to take a look around:
[1,3] in example.rb
1: require 'byebug'
2:
3: def index
4: articles = Article.find_recent
5: byebug
6: end
(byebug):
At the (byebug)
prompt you can inspect things, like what is actually inside articles
by typing articles
and seeing the return value.
You can also inspect any other value that has been loaded up to the point of this break in your code. In addition, you can continue walking (stepping) through your code by typing: step
. When you are ready to exit out of byebug just type exit
and your code continues as normal.
That's it for today! Did you continue to explore debugging? Share what you learned!
Come back tomorrow for the next installment of 49 Days of Ruby! You can join the conversation on Twitter with the hashtag #49daysofruby.
Posted on April 24, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024