Welcome to this tutorial on using Pry and Byebug for debugging in Ruby.
Our goal in this tutorial is to get you comfortable with using Pry and Byebug, two powerful debugging tools that allow you to pause your code execution, inspect variables and follow the flow of your code.
By the end of this tutorial, you will have a solid understanding of how to set breakpoints, step through your code, inspect variables and navigate code execution.
Prerequisites
Before we get started, make sure you have Ruby installed on your system. Some familiarity with Ruby syntax would be helpful.
First, we need to install Pry and Byebug. Add these lines to your application's Gemfile:
gem 'pry'
gem 'byebug'
Then execute bundle install
to install the gems.
Pry is an interactive shell for Ruby, which allows you to inspect and manipulate code directly.
You can use it by simply adding binding.pry
anywhere in your code where you want to pause execution.
def find_square_root(number)
binding.pry
Math.sqrt(number)
end
When your code hits binding.pry
, it will pause, allowing you to inspect variables, call methods, and so on.
Byebug allows you to set breakpoints in your code, step through the execution, and inspect variables.
You can start using Byebug by adding byebug
anywhere in your code where you want to pause execution.
def calculate_sum(numbers)
sum = 0
numbers.each do |number|
byebug
sum += number
end
sum
end
def divide(x, y)
binding.pry
x / y
end
divide(10, 2)
Here, when the divide
method is called, the code will pause at binding.pry
. You can then inspect the variables x
and y
, and even modify them.
def find_max(numbers)
max = numbers[0]
numbers.each do |number|
byebug
max = number if number > max
end
max
end
find_max([5, 3, 9, 1, 7])
Here, the code will pause at byebug
during each iteration. You can inspect the number
and max
variables, step to the next line, or continue execution.
In this tutorial, we learned about two powerful Ruby debugging tools: Pry and Byebug. We learned how to pause our code execution, inspect variables, and step through the code.
For further learning, try to debug more complex code with these tools. You can also explore their advanced features, such as conditional breakpoints.
Here are some additional resources:
- Pry Documentation
- Byebug Documentation
Exercise 1: Write a method that calculates the factorial of a number. Use Pry to debug it.
Exercise 2: Write a method that sorts an array of numbers in descending order. Use Byebug to debug it.
Exercise 3: Write a method that finds the duplicate numbers in an array. Use both Pry and Byebug to debug it.
Happy Debugging!