The interactive ruby (irb) interpreter allows ruby coders to try things out in trial ‘sandbox’. It is great for typing in a few ruby commands and get a result. For example you can just type in:
> 2 + 3
=> 5
and it gives you the result right away!
Each time you enter irb, the slate is clean. So, if you have to enter several ‘require’ commands, for example, they have to be typed in each and every time.
Fortunately, irb has a configuration file to makes things easier for you! Let’s say you are testing a new Class that you are writing. And, every time you enter irb you need to type “require ‘./my_new_class'”. You can add that line to your .irbrc file and the file will be read by irb each time you start up irb!
But the fun doesn’t stop there. You can colorize your irb! Try out the following commands in your irb. Or, better yet, just add them to your .irbrc file:
require 'rubygems' require 'wirble' Wirble.init Wirble.colorize
You can also create some quick use commands by creating an alias. Here we add the following line to our .irbrc file so we can just type ‘q’ to leave irb, rather than having to type ‘exit':
alias q exit
Another cool trick you can do is to customize new methods for irb. Most rubyists already know that in irb you can ask for a list of all the methods that can be used on an object. For example, here we ask for all the methods that can be performed on a text string:
> “some text”.methods
This, of course, list ALL the methods that can be used against a string INCLUDING all the methods string inherited from object. Usually we don’t care about all those extra methods that were inherited. So we can add a method to the object class to give us methods, but not the methods from the object class. Try adding this to your .irbrc file…
class Object # Return only the methods not present on basic objects def m? methods = (self.methods - Object.instance_methods).sort end end
Now, whenever we are in irb, we can just type:
> “some text”.m?
and we will bet back a list of methods that can be used on a string, and they will be sorted.
I hope you enjoy these tricks!
Special thanks go out to the Jeffrey Matthais at Boulder Ruby Group meeting who taught these great tricks!