Last Updated: February 25, 2016
·
2.081K
· scrogson

Evaluate Ruby in Vim

I'm sure we're all used to using IRB to test drive little chunks of code. But let's face it, writing multi-line code in IRB is not as easy in comparison to using your editor.

One thing I've recently learned, that I've found extremely helpful is a tool called xmpfilter which is available in the rcodetools gem.

gem install rcodetools

xmpfilter is a small tool that can be used to annotate source code with intermediate results (a bit like irb --simple-prompt but only for the lines explicitly marked with # =>)

With the help of vim-ruby-xmpfilter you can easily evaluate lines of ruby code inline with the touch of a few key strokes.

nmap <buffer> <F4> <Plug>(xmpfilter-run)
xmap <buffer> <F4> <Plug>(xmpfilter-run)
imap <buffer> <F4> <Plug>(xmpfilter-run)

nmap <buffer> <F3> <Plug>(xmpfilter-mark)
xmap <buffer> <F3> <Plug>(xmpfilter-mark)
imap <buffer> <F3> <Plug>(xmpfilter-mark)
%w(ruby rocks).join(' ').upcase

Press F3 to insert the hash-rocket comment

%w(ruby rocks).join(' ').upcase # =>

Press F4 to evaluate the code inline

%w(ruby rocks).join(' ').upcase # => "RUBY ROCKS"

Enjoy!