Indentation Checking in Ruby

Author: Szymon Lipiński
Published at: 2010-05-23

In Python blocks have to be indented just because the indentation level defines the logic. In C/C++/Java there are { and } while in Ruby there is begin and end. Of course indenting is helpful. Just like syntax coloring in editor.

In Ruby you can do whatever you want with the indentation. That’s not a problem. Every good editor can fix the code layout due to some rules. Normally I use VIM for all those scripting languages, for programming in Ruby and Python too. In VIM after opening any file I can do the magic command:

    <ESC>ggVG=

and the code is nicely intended. Of course that doesn’t work in Python as changing the spaces at the beginning of each line usually change the program logic.

Let’s take this simple code in Ruby (I know, indentation is quite bad):

class Example
    def test?
        puts "YEA"
  end
  end

x = Example.new
puts "Is this a test?"
x.test?

That works and running that just prints two lines on console:

    $ ruby1.8 x.rb
    Is this a test?
    YEA

Ruby1.9 works too:

    $ ruby1.9 x.rb
    Is this a test?
    YEA

For Ruby 1.9 there is magical parameter -w. Using that can be a little bit surprising:

    $ ruby1.9 -w x.rb
    ruby1.9: warning: mismatched indentations: line 4:'def' and line 6:'end'
    ruby1.9: warning: mismatched indentations: line 3:'class' and line 7:'end'
    Is this a test?
    YEA

Using that special nice command in VIM changed the code to this:

class Example
    def test?
        puts "YEA"
    end
end

x = Example.new
puts "Is this a test?"
x.test?

And now the output is without any errors:

    $ ruby1.9 -w x.rb
    Is this a test?
    YEA

For me this is quite surprising, I cannot just wait to have another switch: --treat-all-warnings-as-error so you couldn’t compile the Ruby code if there is no correct indentation.

The comments are disabled. If you want to write something to me, you can use e.g. Twitter.