How to Debug Using byebug (Ruby Debugger)
—byebug` is a powerful debugging gem for Ruby applications, particularly useful in Ruby on Rails.
🛠️ Installation
| Scenario | Instructions |
|---|---|
| Rails Project | Ensure gem 'byebug' is present in your Gemfile (usually in the development and test groups), then run bundle install. |
| Standard Ruby Project | Run the command gem install byebug and add require 'byebug' at the top of your Ruby file. |
🛑 Setting a Breakpoint
Simply add the keyword byebug to the line of code where you want the program to pause:
def process_data(data)
intermediate_result = data.map(&:upcase)
byebug # The program will stop here
final_result = intermediate_result.join(', ')
return final_result
end
When the program executes this line, the debugger shell will appear in your Terminal.
📝 Essential byebug Commands
Here are the commands you use while inside the (byebug) session:
| Command | Shorthand | Function | Explanation |
|---|---|---|---|
| next | n |
Execute the next line. | Does not step into methods called on the current line. |
| step | s |
Execute the next line. | Steps into the called method (if any). |
| continue | c |
Continue execution. | Runs the program normally until the next breakpoint or termination. |
| finish | fin |
Run until the current method exits. | Stops on the line immediately following the method call. |
p |
Print value. | Prints the value of a variable or expression (e.g., p data). |
|
| pp | Pretty print value. | Prints the value in a more readable, formatted way. | |
| break | b |
Set a new breakpoint. | Sets a break at a line (e.g., b 25) or a method (b MyClass#method). |
| list | l |
Display code. | Shows the source code surrounding the current line. |
| where | w |
Display stack trace. | Shows the sequence of method calls that led to the current location. |
| quit | q |
Exit and stop program. | Exits the debugger and terminates the program execution. |