Economy of Effort

Twitter LinkedIn GitHub Mail RSS

Vim Tricks For Ruby Hashes

I have a couple of functions in my .vimrc for manipulating Ruby hashes.

The first one is to convert hashes from Ruby 1.8 style into Ruby 1.9+ style, eg.

# before
:symbol_key => ‘value’
# after
symbol_key: ‘value’

I create this function for both Normal and Visual modes to allow updating either a selected hash, or the entire file.

function! RubyHashesAll()
:%s/:([^ ])(\s)=>/\1:/ge
function! RubyHashesSelected()
:‘<,’>s/:([^ ])(\s)=>/\1:/ge
nmap <Leader>rhh :call RubyHashesAll()<CR>
vmap <Leader>rhh :call RubyHashesSelected()<CR>

Next, I have one for taking a hash and extracting an array of the hash keys.

# before
{ ‘one’ => two, :three => ‘four’, five: 6 }
# after
[‘one’, :three, :five]

Here, I have the command bound only in Visual mode, as I don’t see a case where I’d want to do this globally.

function! RubyExtractHashKeys()
vmap <Leader>rhe :call RubyExtractHashKeys()<CR>

The regexes can probably be improved to fix some edge cases, and I’m certain there’s a way in Vim to make it so that I don’t have to define the All and Selected versions of RubyHashes as separate functions. But these do the job for me now, until I reach a higher plane of Vim mastery.