Debugging in Ruby

Ruby Debugging using Debug Gem

A software bug is an error that happens in an application causing it to return an invalid result or to function incorrectly. Don't worry if the code you write has bugs. It's expected. Bugs are an inevitable part of writing code. Even developers with years of experience have probably never written a bug-free application. Once bugs are found in an application, developers use a process called debugging to track down what is causing those errors and find a fix for them.

Debugging in Ruby

debug is Ruby's new default debugger included from Ruby 3.1. The new debugger has replaced byebug the debugger in Rails 7. debug gem provides a wide range of functionalities and has good performance too. Find below features provided by debugging gem:

  • It performs better than previous gems like lib/debug.rb and byebug.
  • It's extensible. The application can add debugging support in several ways. You can use it rdbg command on the command line or use `binding.pry` method in ruby/rails methods.
  • It comes with a VSCode extension for seamless integration.

The new gem was announced at RubyConf.

How to Use debug Gem

Find below the example code to use debug gem. Here binding.pry the method is used for adding breakpoints.

$ ruby sample.rb                       # Sample program using debug gem
require 'debug'                        # require 'debug' gem   

a = 1
b = 2
sum = a+b
binding.break                          # Program will stop here

p sum
c = 3
d = 4
diff = d-c
binding.break                          # Program will stop here

p diff

You can try more examples from the github.

Integration Support with VSCode

Below steps can be followed to integrate debug  gem in VSCode.

  • Search and Install VSCode rdbg Ruby Debugger extension in your VSCode.
  • While writing this blog, the latest version is v0.0.11  
  • Open the ruby file you want to debug in the VSCode.
  • Register the breakpoint by clicking on the line you want to set the breakpoint and pressing the F9 key.
  • Start the debugging by pressing the F5 key or by selecting Start debugging in the Run menu.

Conclusion

Debugging tools are the most sophisticated way of finding bugs in software. debug gem also works nicely with the Rails app and ticks all boxes to find the most complex bugs in your code.

Abhay

Abhay

Pune, India