Using VIM as an Interactive Ruby Environment

I’m working on some ruby code today on a cleanly installed vim. I decided to improve my editing experience a bit and found some a couple enhancements that work quite nice together.

Evaluate ruby with the press of a button

You can see the source of this tip from the vim wiki. I find the last bit of code the best of them:

function! Ruby_eval_vsplit() range
  let src = tempname()
  let dst = "Ruby Output"
  " put current buffer's content in a temp file
  silent execute ": " . a:firstline . "," . a:lastline . "w " . src
  " open the preview window
  silent execute ":pedit! " . dst
  " change to preview window
  wincmd P
  " set options
  setlocal buftype=nofile
  setlocal noswapfile
  setlocal syntax=none
  setlocal bufhidden=delete
  " replace current buffer with ruby's output
  silent execute ":%! ruby " . src . " 2>&1 "
  " change back to the source buffer
  wincmd p
endfunction

vmap <silent> <F7> :call Ruby_eval_vsplit()<cr>
nmap <silent> <F7> mzggVG<F7>`z
imap <silent> <F7> <ESC><F7>a
map <silent> <S-F7> <C-W>l:bw<cr>
imap <silent> <S-F7> <ESC><S-F7>a

Select some ruby code and hit F7 or hit F7 to evaluate the entire buffer. A new split is automatically opened or it uses an existing split if one is available.

Create a usable scratch buffer

Now if you combine that with the scratch.vim plugin you have a nice little 1-2 punch combination of ruby prototyping bliss. Nub tip: download scratch.vim put into $VIMDIR\vimfiles\plugins\ restart your editor and type :Scratch then type :set ft=ruby to get ruby syntax highlighting in the scratch buffer.

I may be wrong but I think this stuff comes with the emacs ruby mode for free (scratch buffer is a built-in emacs feature).

This entry was posted in ruby, vim. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>