Practical Sorcery with irb

When you run irb, the Ruby REPL, it loads the Ruby script at ~/.irbrc, if it exists. My .irbrc file has gotten kind of big lately, and the tricks it adds to my shell are great, so I thought I’d pull it apart and show you the magic inside.

Includes and setup

require 'pp' require 'rubygems' # wirble is amazing require 'wirble' Wirble.init Wirble.colorize IRB.conf[:AUTO_INDENT] = true 

This stuff is all pretty trivial, but incredibly useful. pp is a library that comes with Ruby that prints out nested hashes and arrays in a readable format with indentation. Requiring rubygems up front almost always saves you a line of code. It also lets you require the gem wirble, which gives you cross-session history, colored output, and auto-completion.

IRB.conf[:AUTO_INDENT] = true does exactly what it sounds like: when you write code that would normally have an indent after it, like the beginning of a block, irb indents the next line.

class Object # get all the methods for an object that aren't basic methods from Object def my_methods (methods - Object.instance_methods).sort end end 

When I need to look up methods on an object, I’m always bombarded with a mess of methods on Object. This just gets rid of them for me.

# from http://themomorohoax.com/2009/03/27/irb-tip-load-files-faster def ls %x{ls}.split("\n") end def cd(dir) Dir.chdir(dir) Dir.pwd end def pwd Dir.pwd end 

ls is copied from a person who has the same problem as me: always typing ls inside irb. This just makes that work. I figured as long as I was doing that, I might as well implement the shell commands cd and pwd.

# also from http://themomorohoax.com/2009/03/27/irb-tip-load-files-faster def rl(file_name = nil) if file_name.nil? if !@recent.nil? rl(@recent) else puts "No recent file to reload" end else file_name += '.rb' unless file_name =~ /\.rb/ @recent = file_name load "#{file_name}" end end 

This is some slick magic to help you reload Ruby code inside irb. Normally, you can re-read a file with load "<filename>.rb", which works well, but is a lot to type over and over. rl lets you just type rl "<filename>", and once you’ve called it once, you can just type rl to reload the same file again.

alias p pp alias quit exit 

Finally, I dropped two aliases into .irbrc. pp is so great that I prefer to use it over p, and I have an inability to remember to type exit instead of quit, so I just fixed that.

You can find the entire .irbrc file at http://gist.github.com/86875. If you have any irb tips of your own, let us know in the comments!

Sign up for The Viget Newsletter

Nobody likes popups, so we waited until now to recommend our newsletter, a curated periodical featuring thoughts, opinions, and tools for building a better digital world. Read the current issue.