Our Code Standards
Use soft-tabs with a two space indent.
Keep each line of code to a readable length. Unless you have a reason to, keep lines to fewer than 100 characters.
Never leave trailing whitespace.
End each file with anewline.
Use spaces around operators, after commas, colons and semicolons, around
{
and before}
.
No spaces after
(
,[
or before]
,)
.
No spaces after
!
.
Indent
when
as deep ascase
.
Use empty lines between
def
s and to break up a method into logical paragraphs.
Classes
Avoid the usage of class (
@@
) variables due to their unusual behavior in inheritance.
Use
def self.method
to define singleton methods. This makes the methods more resistant to refactoring changes.
Avoid
class << self
except when necessary, e.g. single accessors and aliased attributes.
Indent the
public
,protected
, andprivate
methods as much the method definitions they apply to. Leave one blank line above them.
Avoid explicit use of
self
as the recipient of internal class or instance messages unless to specify a method shadowed by a variable.
Collections
Prefer
%w
to the literal array syntax when you need an array of strings.
Use
Set
instead ofArray
when dealing with unique elements.Set
implements a collection of unordered values with no duplicates. This is a hybrid ofArray
's intuitive inter-operation facilities andHash
's fast lookup.Use symbols instead of strings as hash keys.
Documentation
Use TomDoc to the best of your ability. It's pretty sweet:
Exceptions
Don't use exceptions for flow of control.
Rescue specific exceptions, not
StandardError
or its superclasses.
Hashes
Use the Ruby 1.9 syntax for hash literals when all the keys are symbols:
Use the 1.9 syntax when calling a method with Hash options arguments or named arguments:
If you have a hash with mixed key types, use the legacy hashrocket style to avoid mixing styles within the same hash:
Keyword Arguments
Keyword arguments are recommended but not required when a method's arguments may otherwise be opaque or non-obvious when called. Additionally, prefer them over the old "Hash as pseudo-named args" style from pre-2.0 ruby.
So instead of this:
Do this, which is much clearer.
Naming
Use
snake_case
for methods and variables.Use
CamelCase
for classes and modules. (Keep acronyms like HTTP, RFC, XML uppercase.)Use
SCREAMING_SNAKE_CASE
for other constants.The names of predicate methods (methods that return a boolean value) should end in a question mark. (i.e.
Array#empty?
).The names of potentially "dangerous" methods (i.e. methods that modify
self
or the arguments,exit!
, etc.) should end with an exclamation mark. Bang methods should only exist if a non-bang method exists. (More on this.
Percent Literals
Use
%w
freely.
Use
%()
for single-line strings which require both interpolation and embedded double-quotes. For multi-line strings, prefer heredocs.
Use
%r
only for regular expressions matching _more than _one '/' character.
Regular Expressions
Avoid using $1-9 as it can be hard to track what they contain. Named groups can be used instead.
Be careful with
^
and$
as they match start/end of line, not string endings. If you want to match the whole string use:\A
and\z
.
Use
x
modifier for complex regexps. This makes them more readable and you can add some useful comments. Just be careful as spaces are ignored.
Requires
Alwaysrequire
dependencies used directly in a script at the start of the same file. Resources that will get autoloaded on first use—such as Rails models, controllers, or helpers—don't need to be required.
This not only loads the necessary dependencies if they haven't already, but acts as documentation about the libraries that the current file uses.
Strings
Prefer string interpolation instead of string concatenation:
Use double-quoted strings. Interpolation and escaped characters will always work without a delimiter change, and
'
is a lot more common than
"
in string literals.
Avoid using
String#+
when you need to construct large data chunks. Instead, useString#<<
. Concatenation mutates the string instance in-place and is always faster thanString#+
, which creates a bunch of new string objects.
Syntax
Use
def
with parentheses when there are arguments. Omit the parentheses when the method doesn't accept any arguments.Never use
for
, unless you know exactly why. Most of the time iterators should be used instead.for
is implemented in terms ofeach
(so you're adding a level of indirection), but with a twist -for
doesn't introduce a new scope (unlikeeach
) and variables defined in its block will be visible outside it.
Never use
then
for multi-lineif/unless
.
Avoid the ternary operator (
?:
) except in cases where all expressions are extremely trivial. However, do use the ternary operator(?:
) overif/then/else/end
constructs for single line conditionals.
Use one expression per branch in a ternary operator. This also means that ternary operators must not be nested. Prefer
if/else
constructs in these cases.
The
and
andor
keywords are banned. It's just not worth it. Always use&&
and||
instead.Avoid multi-line
?:
(the ternary operator), useif/unless
instead.Favor modifier
if/unless
usage when you have a single-line body.
Never use
unless
withelse
. Rewrite these with the positive case first.
Don't use parentheses around the condition of an
if/unless/while
.
Prefer
{...}
overdo...end
for single-line blocks. Avoid using{...}
for multi-line blocks (multiline chaining is always ugly). Always usedo...end
for "control flow" and "method definitions" (e.g. in Rakefiles and certain DSLs). Avoiddo...end
when chaining.
Avoid
return
where not required.
Use spaces around the
=
operator when assigning default values to method parameters:
While several Ruby books suggest the first style, the second is much more prominent in practice (and arguably a bit more readable).
Using the return value of
=
(an assignment) is ok.
Use
||=
freely to initialize variables.
Don't use
||=
to initialize boolean variables. (Consider what would happen if the current value happened to befalse
.)
Avoid using Perl-style special variables (like
$0-9
,$
, etc. ). They are quite cryptic and their use in anything but one-liner scripts is discouraged. Prefer long form versions such as$PROGRAM_NAME
.Never put a space between a method name and the opening parenthesis.
If the first argument to a method begins with an open parenthesis, always use parentheses in the method invocation. For example, write
f((3 + 2) + 1)
.Use
_
for unused block parameters.
Don't use the
===
(threequals) operator to check types.===
is mostly an implementation detail to support Ruby features likecase
, and it's not commutative. For example,String === "hi"
is true and"hi" === String
is false. Instead, useis_a?
orkind_of?
if you must.Refactoring is even better. It's worth looking hard at any code that explicitly checks types.
Last updated