As we are starting to write code, it becomes apparent that some code just looks better than other code. I’m pretty sure the Ruby interpreter doesn’t care, but source code is really a document of the product that the code produces so it is important that it be readable and understandable to others.
Ruby is pretty expressive, and it seems to offer a lot of flexibility with the syntax. This could lead to a lot of variation in style. Just as there are standards for style in the production of written works, so there are for programmers.
For Ruby that style guide seems to be: BBatsov’s Ruby Style Guide.
It’s an envolving document with a lot of examples of good and bad coding style, some of which I am certain are parts of large philosophical debates. In any event as a new Rubyist I feel it is important to develop good habits. I read through the whole document and here some picks for new programmers to be aware of when writing code, based on the sort of code we are writing now.
All examples courtesy of BBatsov.
Limit lines to 80 characters.
Avoid trailing whitespace.
Use spaces around operators, after commas, colons and semicolons, around
}. Whitespace might be (mostly) irrelevant to the Ruby interpreter, but its proper use is the key to writing easily readable code.
1 2 3 4
No spaces after
(, [ or before
Use empty lines between defs and to break up a method into logical paragraphs.
1 2 3 4 5 6 7 8 9 10 11
Use spaces around the = operator when assigning default values to method parameters:
1 2 3 4 5 6 7 8 9
Add underscores to large numeric literals to improve their readability.
1 2 3 4 5
Don’t use block comments. They cannot be preceded by whitespace and are not as easy to spot as regular comments.
1 2 3 4 5 6 7 8 9
That’s probably enough to get started. There is also a very useful gem RuboCop that will tell you where you are diverging from these recommendations.