Andrés

20 November 2023

💎Ruby Tip💎 Interactive debugging without the need for gems.
Discover a simple and fast way to debug in Ruby without installing additional gems. With the Binding class and the integrated IRB console, you can explore and modify the execution context to resolve errors efficiently.

There are different popular gems in the Ruby universe with various functionalities and different syntaxes to perform interactive debugging. Some of these gems can be byebug or debug. The problem with these gems is that sometimes they need to be installed, configured and have their own commands to learn. This takes some time and many times there is no need for something so complex for such a small bug.

For those cases, we will have the option of using the Binding class. This allows us to encapsulate the execution context at a given point and return it for future use. Binding objects can be created by calling the Kernel#binding method and the console will be raised using the public instance method irb.

With a little bit of code it will be more than clear:

# door.rb
class Door
  def initialize
    @open = false
    binding.irb
    puts "Is the door open: #{@open}"
  end
end

Door.new

Running our small script will open an IRB session with which you can review the context and modify it:

Documentos/scripts/ruby via 💎 v3.2.2
 ruby door.rb

From: door.rb @ line 4 :

    1: class Door
    2:   def initialize
    3:     @open = false
 => 4:     binding.irb
    5:     puts "Is the door open: #{@open}"
    6:   end
    7: end
    8:
    9: Door.new

irb(#):001> @open
=> false
irb(#):002> @open=true
=> true
irb(#):003> exit
Is the door open: true

And that’s it, you can use it to debug your scripts, web scrappers or whatever you are building.

To learn more about using IRB you can visit this documentation

If you liked it feel free to say hi in the comments, I’ll be watching.

Happy coding!

Read More