Do I need to indent Ruby code?

D

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’s 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 usually not throw errors. Still, the improper syntax may cause the parser to misunderstand your code’s intent because of ambiguous white spaces or line breaks.

If it does not 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 the most important reason to indent Ruby code is, 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, this community-driven Ruby Style guide is worth reading. According to the manual, Ruby existed for over 15 years before the guide was created. 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. RuboCop 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.

If you found this post helpful, you might enjoy my other posts about Ruby basics and my experiences in a coding Bootcamp.

Happy Programming!

About the author

Kelly Barkhurst

Designer to Fullstack is my place to geek out and share tech solutions from my day-to-day as a graphic 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

Archives

Categories