Formatting ruby hashes in VIM
I’ve been meaning to write this script for a while. If you’re anal about your whitespace (like I), you’ll often pretty up your ruby hashes to make them easy to read by adding a bit of whitespace to the keys before the =>. I wrote a ruby script to do this automatically!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
#!/usr/bin/env ruby # format_hash.rb # # Formats ruby hashes # a => 1 # ab => 2 # abc => 3 # # becomes # a => 1 # ab => 2 # abc => 3 # # http://rhnh.net lines = [] while line = gets lines << line end indent = lines.first.index(/[^\s]/) # Massage into an array of [key, value] lines.collect! {|line| line.split('=>').collect {|line| line.gsub(/^\s*/, '').gsub(/\s*$/, '') } } max_key_length = lines.collect {|line| line[0].length}.max # Pad each key with whitespace to match length of longest key lines.collect! {|line| line[0] = "%#{indent}s%-#{max_key_length}s" % ['', line[0]] line.join(' => ') } print lines.join("\n") |
Put that in your path, then in VIM you can run the following command to format the current selection:
The Switch to VIM
I’m been meaning to try out Vim for a while, especially since I now use two different platforms/editors for development (mac/textmate at work, linux/jedit at home). Finally got some time to try it out this weekend, and initial reports are positive! The thing that strikes me the most is how quickly you can navigate/select things without using the mouse. Vim’s navigation shortcuts are like CTRL-(LEFT|RIGHT) on crack. Regex search forward and back, move by multiple lines, seek to next/prev char. I haven’t internalized this navigation yet and already I’m loving it. Give me some experience and I’ll become an absolute machine. It’s a bit weird because I’m using colemak, so the “stick to the home row” mantra doesn’t really apply, but overall it’s still quite bearable. I need to figure out how to replicate the Apple-T shortcut in textmate (quick swith to file) and I think I’ll be sold. I’ll use it at work for the week and see how things go. For reference, I found the tutorial on the vi-improved site to be quite helpful.