the blog
Back to -Blog

Ruby Code Auto-Formatting

How to prettify your Ruby code in seconds…
by Huw Collingbourne
Tuesday 20 March 2007.

We received a feature request in the forum recently from a user who wanted to know if we might, at some future date, be able to add a tool to auto-format Ruby code. It turns out that we already have this feature. It seems we are now getting to the stage in the Developer Edition of Ruby In Steel where it’s hard to see the wood from the trees. So, on the assumption that this is something that other people may have missed too, let me explain how it works…

Ruby auto-formatting can be particularly useful when trying to make sense of other people’s code. Many of the standard libraries supplied with Ruby are thousands of lines in length; single classes and methods may often be hundreds of lines long and the code indenting is frequently irregular; all of which can make it very difficult to match up all those ends with whichever keywords (def, class, if, unless and so on) to which they belong.

Code collapsing can help to sort out the hidden structure of long code files. And Ruby In Steel’s keyword-end matching (like bracket-matching but for keywords) is also a useful tool (press Ctrl+] to use that).

Keyword..end matching

But better still is the ability to reformat the entire document, or a marked area, so that each end lines up with its matching keyword and any code contained between them is indented. The picture below shows an example of what I mean. This is part of one of the files in the IRB library (ruby-lex.rb). It’s a file containing about 1150 lines of code which is not consistently indented. By selecting Format Document (Edit->Advanced->Format Document) or by pressing a hotkey (Ctrl+E, D is the default), I can have the indenting of the entire source code of the file regularised almost instantly…

Auto-formatting a Ruby document
Bookmark and Share   Keywords:  ide
© SapphireSteel Software 2014