Style Guide¶
Ruby¶
Indentation¶
Ruby code should be indented with 2 spaces (never hard tabs). Lines should be limited to 79 columns. There should never be trailing white space.
Method Definitions¶
Ruby method definitions should include parenthesis if there any arguments, and no parenthesis if there aren’t arguments.
Good:
def f
end
def f(a, b)
end
Bad:
def f()
end
def f a, b
end
There should be spaces around the =
for default arguments.
Good:
def f(a = nil)
end
Bad:
def f(a=nil)
end
Blocks¶
Spaces should be used around the pipes and braces in blocks.
Good:
arr.map { |x| x * 2 }
Bad:
arr.map {|x|x * 2}
When testing for a block, prefer explicit if block
to block_given?
.
Good:
def f(&block)
if block
end
end
Bad:
def f
if block_given?
end
end
Hashes and Arrays¶
There should be no spaces around either brackets or braces, spaces should always follow commas and go around hash rockets. Hash rockets should be used in preference to “new-style” hashes.
Good:
[1, 2, 3]
{:abc => 45}
Bad:
[1,2]
{ :abc=>23 }
{abc: 23}
Exceptions¶
Exceptions should be raised using ExceptionClass.new
, rather than the
2-argument form of raise
. Error messages should be compatible with CRuby
whenever reasonable.
Good:
raise ArgumentError.new("A message")
Bad:
raise ArgumentError, "A message"
Statements¶
Never use and
, or
, or not
, their precedence is confusing, prefer
&&
, ||
, and !
.
The ternary operator should only be used for selecting a value, never for a side effect.
Good:
(a > b) ? a : b
Bad:
foo ? self.bar! : nil