Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails coding standards - Why 2 space indentation?

In reading about rails coding standards, it seems clear that 2 spaces is generally accepted as the way to do things. Why has this gained traction? Is it just the most widely used practice and therefor best to use for consistency, or is there another reason it is actually better than tabs or a different number of spaces?

like image 901
Lee Quarella Avatar asked Jul 19 '11 02:07

Lee Quarella


People also ask

Why does the code under the if need to be indented two spaces Ruby?

Because ruby has built in support for anonymous blocks, lots of ruby code ends up being nested more than in other languages. 2 space indents allow for more nesting in a given width.

Why do people use spaces for indentation?

If a couple of people work on same file it is highly possible to generate unnecessary conflicts. Using spaces instead of tabs makes it possible to easily catch such an accidental space on eyeball and this is probably a reason, why using them become a standard.

How many spaces are used for code indentation?

Code MUST use an indent of 4 spaces, and MUST NOT use tabs for indenting. Note that this doesn't mean "every line of code in a file should be indented by exactly 4 spaces", it means "each time you open a new structure which requires indenting, increase the indent by exactly 4 spaces".

Does Ruby care about indentation?

“Ruby doesn't care about whitespace (spaces and blank lines), so the indentation of the print statement isn't necessary. However, it's a convention that Rubyists (Ruby enthusiasts) follow, so it's good to get in the habit now. The block of code following an if should be indented two spaces.”


2 Answers

It's a matter of convention. The really important thing is consistency.

Most (but not all) developers prefer spaces to tabs because they look the same regardless of any particular text editor / ide setting. http://www.ecyrd.com/JSPWiki/wiki/WhyTabsAreEvil

Two spaces over four is also a matter of convention. Ruby code aims to minimize extra characters, and I suppose extra whitespace goes against this trend.

like image 128
Brian Glick Avatar answered Sep 24 '22 14:09

Brian Glick


  1. Because ruby has built in support for anonymous blocks, lots of ruby code ends up being nested more than in other languages. 2 space indents allow for more nesting in a given width.
  2. Spaces always look the same in every editor (consistent look and feel)
  3. Convention
like image 26
bwv549 Avatar answered Sep 22 '22 14:09

bwv549