Do I need to indent Ruby code?


Indenting Ruby code is the best practice; however, Ruby code executes without proper indentation.

Standard indentation for Ruby is two spaces per indentation level.

That’s as simple as clicking your space bar twice. Two and four spaces are sometimes known as soft tabs. (Ruby standard indentation by default is NOT created by clicking your keyboard tab button; however, it is possible to set your editor to insert spaces when you click your tab button instead of inserting a tab.)

Unlike other programming languages, proper Ruby syntax is often not required and will often not throw errors, but improper syntax may cause the parser to misunderstand your code’s intent because of ambiguous white spaces or line breaks.

If it doesn’t error, then why indent?

Proper Ruby indentation creates useful visual indicators and increases readability. For instance, indenting visually indicates which portions of code are nested within a Ruby conditional statement or within a Ruby class.

Arguably most important, consistent formatting makes it easier for programmers to work together. For this reason, there is a Ruby Style Guide that recommends best practices for real-world Ruby programmers.

The Ruby Style Guide

If you’re hoping to or currently working as a real-world Ruby programmer, then this community-driven Ruby Style guide is worth a read. Interestingly, according to the guide, Ruby existed for over 15 years before the guide was created, so as you can imagine, there is still much ground to cover to create a unified industry standard.

The Ruby Style Guide -  includes guidance on how to indent ruby code
The Ruby Style Guide – includes guidance on how to indent ruby code

Tools for Ruby Beautification + More

There are many tools intended to help you format your Ruby code. For VS Code users, there are over 200 Ruby-specific plugins worth exploring.

RuboCop is a Ruby static code analyzer and formatter, based on the Ruby Style Guide. It is incorporated into the VS Code Ruby plugin.

Other Ruby-formatting-specific VS Code plugins are:

Online, TutorialsPoint is one of many services providing a free Online Ruby Formatter that allows you to copy and paste your code for beautification.

About the author

Kelly Barkhurst

Designer to Fullstack is my place to geek out and to share tech solutions from my day-to-day as a designer, programmer, and business owner (portfolio). I also write on Arts and Bricks, a parenting blog and decal shop that embraces my family’s love of Art and LEGO bricks!

Add comment

By Kelly Barkhurst

Recent Posts