Ruby IRB tip: Try again faster
Background
It looks like I’m not the only one who plays in IRB a lot. My previous IRB post got some attention from Clinton Nixon at Viget labs. His post on IRB has my earlier tips, as well as some other ones.
If you didn’t get a chance to read my first post, here’s the code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
def ls %x{ls}.split("\n") end def fl(file_name) file_name += '.rb' unless file_name =~ /\.rb/ @@recent = file_name load "#{file_name}" end def rl fl(@@recent) end |
Basically, instead of having to type ‘load “foo.rb”’ every time you change a file, you can first type ‘fl “foo.rb”’ and then type “rl” each time thereafter.
This has been working great for me, and these methods have gotten a lot of use.
New tip
However, one thing that bugs me is that I end up doing this a lot:
1) Typing code in vim 2) Typing rl in irb 3) Pressing up twice to get my last history item 4) pressing enter to try out the method again
For example, if I had a syntax error or something and I want to try calling a method again, I have to do 5 steps.
Here’s my simple solution to this:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
def rt rl eval(choose_last_command) end # prevent 'rt' itself from recursing. def choose_last_command real_last = Readline::HISTORY.to_a[-2] real_last == 'rt' ? @@saved_last : (@@saved_last = real_last) end |
This lets me both reload the file and retry the code in just one step. Very useful.
April 07, 2009

