Debugging helps you find and fix mistakes in your code. Pry and Byebug let you pause your program and look inside to understand what is happening.
0
0
Debugging with pry and byebug in Ruby
Introduction
When your program is not working as expected and you want to see the values of variables step-by-step.
When you want to stop your program at a certain line to check what is going on.
When you want to try out code commands inside your program while it is paused.
When you want to understand why a loop or condition is not behaving correctly.
When you want to learn how your code flows by moving through it slowly.
Syntax
Ruby
require 'pry' # Insert this line where you want to pause binding.pry # For byebug require 'byebug' # Insert this line where you want to pause byebug
Use binding.pry or byebug inside your code where you want to pause.
Make sure you have installed the gems pry and byebug before using them.
Examples
This pauses the program before adding
x and y. You can check the values of x and y in the Pry console.Ruby
require 'pry' x = 10 y = 20 binding.pry sum = x + y puts sum
This pauses inside the
greet method so you can see the value of name before printing.Ruby
require 'byebug' def greet(name) byebug puts "Hello, #{name}!" end greet('Alice')
Sample Program
This program pauses inside the loop for each number. You can check the value of num before it prints double the number.
Ruby
require 'pry' numbers = [1, 2, 3] numbers.each do |num| binding.pry puts num * 2 end
OutputSuccess
Important Notes
When the program pauses, you can type variable names to see their values.
Type continue or c to resume the program after pausing.
Use debugging to learn and fix problems step-by-step, not just to find errors.
Summary
Debugging with Pry and Byebug lets you pause and explore your code while it runs.
Insert binding.pry or byebug where you want to stop and check variables.
This helps you understand your code better and fix mistakes easily.