Swap Ruby block styles

4.1
(18)

I do a respectable amount of software development in Ruby. In Ruby, code blocks can be surrounded by the curly braces or begin and end keywords. The following two code examples are equivalent functionally:

@collection.each { |item| puts item }

@collection.each do |item|
  puts item
end

The former style works well when the code block contains one statement and is simple to understand. But as code blocks become more complex blocks will grow to span more lines or statements. A generally accepted (and expected) convention is to switch from braced to begin and end when the code increases beyond a single statement. I do this often enough to grow tired of the tediousness. Fortunately there is a super vim plugin called Blockle which makes this tedious operation a simple leader mapping.

With the cursor on a {, }, begin, or end keyword <leader>b will switch between curly braces and begin and end. In practice it seems to work best on the open curly brace and begin.

See the example below where I use space b (space is my leader character) to toggle between braces and begin and end.

How useful was this tip?

Average rating 4.1 / 5. Vote count: 18

No votes so far! Be the first to rate this tip.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Written by

Andy Libby

30 Posts

Rider of bicycles. Writer of code. User of Vim.
View all posts

Leave a reply

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