Easy Ruby Examples

03 May 2007

Today I devised a little script to generate Ruby examples showing code and output.

% rubydemo '[1,2,3].inject {|m,o|m+o}'
[1,2,3].inject {|m,o|m+o} #=> 6
% rubydemo 1/0
1/0 #=> #<ZeroDivisionError: divided by 0>

Here’s the script I used for generation. (It could have been one line if I didn’t care so much about exception formatting.)

#!/usr/bin/env ruby
print ARGV.join(" ") + " #=> "
begin
  p(eval(ARGV.join(" "),binding,"(demo)"))
rescue Exception => e
  puts "#<#{e.class}: #{e.message[/.*/]}>"
end

The real killer app, though, is using it in conjunction with IRC. Here’s the alias I used in Irssi.

/alias rd exec -nosh - -out rubydemo $*

Now I need merely do /rd 2+2 to get a beautifully formatted 2+2 #=> 4 in any conversation.