Ruby Style Guide
Based on Chris Neukirchen's Ruby Style Guide.
Formatting:
-
Use UTF-8
-
Use 2 space indent, no tabs.
-
Use Unix-style line endings.
-
Use spaces around operators, after commas, colons and semicolons, around
{
and before}
. -
No spaces after
(
,[
and before]
,)
. -
Use one space before statement modifiers (postfix
if
,unless
,while
anduntil
). -
Indent
when
as deep ascase
. -
Use an empty line before the return value of a method (unless it only has one line), and an empty line between
def
s. -
Use empty lines to break up a long method into logical paragraphs.
-
Keep lines fewer than 80 characters.
-
Avoid trailing whitespace.
-
Don't align variables/constants assignments or hash keys/values vertically.
Syntax:
-
Use
def
with parentheses when there are arguments. -
Use parentheses for method calls when there are arguments, unless it's part of a DSL.
-
Use
&&
and||
for boolean expressions. -
Use
{...}
for single-line blocks anddo...end
for multi-line blocks. -
Avoid
return
where not required. -
Avoid using
return
inside blocks. -
Avoid line continuation (
\
) where not required. -
Avoid using the return value of
=
in comparisons. -
Use
||=
freely. -
Avoid the
and
andor
operators.
Naming:
-
Use
snake_case
for methods. -
Use
CamelCase
for classes and modules. (Keep acronyms like HTTP, RFC, XML uppercase.) -
Use
SCREAMING_SNAKE_CASE
for other constants. -
Use
_
or names prefixed with_
for unused or private variables. -
When defining binary operators, name the argument "other".
Comments:
-
Comments longer than a word are capitalized and use punctuation.
-
Avoid superfluous comments.
The rest:
-
Avoid writing methods that span more than 10 lines.
-
Avoid writing methods that receive more than 3 parameters.
-
Use
def self.method
to define singleton methods. -
Avoid needless metaprogramming.
-
Don't use
rescue
as a predicate. -
Don't use catch-all
rescue
. -
Don't use
case
without anelse
branch. -
Use the hashrocket notation (
=>
) to build a literal Hash. -
Use doublequotes for one-line strings.
General:
-
Code in a functional way, avoid mutation when it makes sense.
-
Do not mutate arguments unless that is the purpose of the method.
-
Do not mess around in core classes when writing libraries.
-
Do not program defensively.
-
Keep the code simple.
-
Don't overdesign.
-
Don't underdesign.
-
Avoid bugs.
-
Read other style guides and apply the parts that don't dissent with this list.
-
Be consistent.
-
Use common sense.