P is for Programming

Comment Ruby code with Vim

March 1, 2012

I’ve recently started using Vim for Ruby/Rails development. As someone who is very new to Vim it has been a steep learning curve, but I’m really enjoying it – it has definitely become my editor of choice. One of the useful little tricks I figured out today is how to comment out a block of Ruby code.

Here’s what to do.

  1. Navigate to the beginning of the first line you want to comment
  2. Press Ctrl + v
  3. Select the lines you want to comment with j and k
  4. Press Shift + i
  5. Press #
  6. Press Esc

Voila! If you want to do the opposite follow steps 1 to 3 and then simply press d.

This is really just multi-line editing. Happy coding.

Tags: Ruby

  1. There’s a Vim plugin called NERDCommenter which comes with the popular Janus bundle.

    With the default mappings, you can press cc to comment out the currently-selected lines, or c to toggle the comments on and off.

    It works across several different languages — notably Ruby, JavaScript and HTML — and can do block comments, nesting and more.

    Of course, the multi-line insert you describe in this post works without a plugin and is great for more than just commenting!

  2. The comments swallowed my angle brackets :-(

    I meant that the default mappings were [Leader]cc to comment and [Leader]c[space] to toggle comments. In my Vim, [Leader] is the default backslash.