back

Ruby IRB tip, load files faster

I often find myself sitting in irb doing this over and over again:

1
2
3
4
5
6
7
8
9
10
11
12
13
14

$ irb
>> load 'foo.rb'
>> do_stuff
Undefined method to_nil for 3:Fixnum

# Then change foo.rb

>> load 'foo.rb'
>> do_stuff
"Success"
>> q
$

The IRB documentation is pretty anemic, but it’s clear that one way of doing this is to use the -r option.

$ irb -r foo.rb
>>

This is the same as ruby -r and just requires the file.

However, this does not help with subsequent loads, as I would still have to type load 'foo.rb' every time I changed the file.

One way to deal with this is to use a ~/.irbrc file. This is a somewhat little known IRB feature that is basically the same as a .bashrc or .profile file, where you can setup your irb env.

So, since since the .irbrc file is in ruby, it would be best to do something like this:

1
2
3
4
5
6

# fast load, uses acronym b/c type it so much
def fl(file_name)
  load "#{file_name}.rb"
end

Now, when you use irb, you can use fl to load a file.

However, this is not very satisfying, as I still have to type a lot to reload the same file over and over, or press the up key until I find it, which I often end up doing. So, still a big waste of time.

So, let’s get a little bit uglier, and do this

1
2
3
4
5
6
7
8
9
10
11

def fl(file_name)
   file_name += '.rb' unless file_name =~ /\.rb/
   @@recent = file_name 
   load "#{file_name}"
end
 
def rl
  fl(@@recent)
end

Now I can type fl 'foo' and then type rl to reload it. Much better.

For more irb tips:

Also, while I’m at it, another useful IRB method I wrote and use is ls. I often accidentally type ls in irb, so it made sense to just define it.

1
2
3
4
5
6
7
8
9
10

# More than one way to do this
# Commented is the ruby way
# uncommentted is my preferred way
def ls
   #entries = instance_eval("Dir.entries(File.dirname(__FILE__))")
   #(entries - ["..", "."]).reverse
   %x{ls}.split("\n")
end

March 27, 2009

  1. Gabriel says:

    You may find a require-based reload handy:

    1
    2
    3
    4
    
       def reload(filename)
         $".delete(filename + ".rb")
         require(filename)
       end
    
    This way you can reload any file that's been required without having to be in its parent directory. For more irb goodies: http://github.com/cldwalker/irbfiles

  2. Mischa says:

    Thanks Gabriel, great tip!