The Interactive Ruby Shell, or irb, is a great tool to use when debugging Ruby code. You can launch it from a shell window and quickly determine where errors in your Ruby code. Obviously irb is not always the best tool to use when debugging a large code base however for quick hints to where errors are in your Ruby code irb will save the day. One thing I noticed was sometimes when creating arrays irb would output the entire array even if you have not called for that output. So I was thinking it would be nice to be able to toggle the verbose output of arrays on or off during troubleshooting. The verbose output of irb is typically very useful so this toggle should only be used in some scenarios. Below is an explanation of how to create a toggle to turn the irb context echo on or off.
Turn Off IRB Debug Output With A Toggle:
- Modify Or Add .irbrc:First you need to add the toggle code to your .irbrc file. This is the file that resides in your home directory and functions similar to .bashrc in the sense that it stores variables or configuration settings for irb like .bashrc does for the bash shell. If you do not already have a .irbrc file then create one with the below code.
- def verbose_toggle
- irb_context.echo ? irb_context.echo = false : irb_context.echo = true
- Toggle IRB Verbose Output:Now start irb and test the new toggle called verbose_toggle from the irb prompt as shown below.
- [web@idev atp]$ irb
- irb(main):001:0> verbose_toggle
- irb(main):002:0> verbose_toggle
- => true
Notice the first time you run the toggle it appears to not work however this actually proves it is working by not showing you the expected return of “=> false”. To turn the normal output back on you simply issue the verbose_toggle command again which will set irb_context.echo back to “true”.
That is all you have to do to be able to easily turn the irb debug output on or off easily. You will be required to add this to the .irbrc file for every user. Also note that it is possible to have a irb configuration file already it could be named .irbrc, irb.rc, _irbrc, or $irbrc. Just make sure to verify that none of these exist before you add a new file with a different name because if .irb.rb exists and you add .irbrc then the settings that are loaded via irb.rc will be lost. The irb console reads the first configuration file it comes across.