Friday, February 20, 2009

irb with autocompletion support

Interactive ruby shell (irb) is a handy tool for exploratory programming in ruby. One of lesser known features in irb is tab autocompletion support. Say, you want to know instance methods of a particular object, you can type the object followed by a dot and then hit a tab. irb will display all instance methods on that object.

Below is an example of methods for a number 1. After you type 1., hit a tab key. (Oh yeah, 1 is an object in ruby)

$ irb -r irb/completion
irb(main):001:0> 1.
1.eql? 1.instance_variable_get 1.prec_f 1.taint
1.__id__ 1.equal? 1.instance_variable_set 1.prec_i 1.tainted?
1.__send__ 1.even? 1.instance_variables 1.pred 1.tap
1.abs 1.extend 1.integer? 1.private_methods 1.times
1.between? 1.fdiv 1.is_a? 1.protected_methods 1.to_a
1.ceil 1.floor 1.kind_of? 1.public_methods 1.to_enum
1.chr 1.freeze 1.method 1.quo 1.to_f
1.class 1.frozen? 1.methods 1.remainder 1.to_i
1.clone 1.hash 1.modulo 1.respond_to? 1.to_int
1.coerce 1.id 1.next 1.round 1.to_s
1.display 1.id2name 1.nil? 1.send 1.to_sym
1.div 1.inspect 1.nonzero? 1.singleton_method_added 1.truncate
1.divmod 1.instance_eval 1.object_id 1.singleton_methods 1.type
1.downto 1.instance_exec 1.odd? 1.size 1.untaint
1.dup 1.instance_of? 1.ord 1.step 1.upto
1.enum_for 1.instance_variable_defined? 1.prec 1.succ 1.zero?


You may scope down results by typing more, say, show all instance methods that start with 'i'.

irb(main):001:0> 1.i
1.id 1.instance_eval 1.instance_variable_defined? 1.instance_variables
1.id2name 1.instance_exec 1.instance_variable_get 1.integer?
1.inspect 1.instance_of? 1.instance_variable_set 1.is_a?


To enable tab completion in irb, you need to start irb with -r irb/completion option. Or if you are already in irb, do 'require irb/completion'.

As a bonus, require irb/completion works in rails script/console too.