LOOPS:
- Never use unless with else. Rewrite these with the positive case first.
BAD
unless success?
message = 'FAIL'
else
message = 'PASS'
end
GOOD
if success?
message = 'PASS'
else
puts 'failure'message = 'FAIL'
end
- Use unless instead of if for negative conditions.
BAD
unless x == 10
...
end
GOOD
if x != 10
...
end
BAD
unless x < 10
...
end
GOOD
if x >= 10
...
end
- Don't use parentheses around the condition of an if/unless/while.
BAD
if (x > 10)
...
end
GOOD
if x > 10
...
end
- Prefer next in loops instead of conditional blocks.
BAD
[0, 1, 2, 3].each do |item|
if item > 1
puts item
end
end
GOOD
[0, 1, 2, 3].each do |item|
next unless item > 1
puts item
end
STATEMENTS:
The and, or, and not keywords are banned. It's just not worth it. Always use &&, ||, and ! instead.
Do not include space inside block parameter pipes. Include one space between parameters in a block. Include one space outside block parameter pipes.
BAD
{}.each { | x, y |puts x }
GOOD
{}.each { |x, y| puts x }
- Don't use extra whitespace in range literals.
BAD
(0 ... coll).each do |item|
GOOD
(0...coll).each do |item|
- Omit parentheses for a method call if the method accepts no arguments.
BAD
nil?()
GOOD
nil?
- Use shorthand self assignment operators whenever applicable
BAD
x = x + y
x = x * y
x = x**y
x = x / y
x = x || y
x = x && y
GOOD
x += y
x *= y
x **= y
x /= y
x ||= y
x &&= y
STRINGS:
- Omit whitespace when doing string interpolation.
BAD
var = "This #{ foobar } is interpolated."
GOOD
var = "This #{foobar} is interpolated."
- Don’t use Object#to_s on interpolated objects. It’s invoked on them automatically.
BAD
message = "This is the #{result.to_s}."
GOOD
message = "This is the #{result}."
GENERAL:
Never leave commented-out code in our codebase.
Use snake_case for naming files and directories
Use block comments if comments are more than 2 lines:
BAD
1st comment line
2nd comment line
3rd comment line
GOOD
=begin
1st comment line
2nd comment line
3rd comment line
=end
FUNCTIONS:
- Function should not accept more than 3 parameters.
More than 3 values should be sent in hash.
BAD
def obliterate(things, gently = true, except = [], at = Time.now)
...
end
GOOD
def obliterate(things, options = {})
options = {
:gently => true, # obliterate with soft-delete
:except => [], # skip obliterating these things
:at => Time.now, # don't obliterate them until later
}
...
end
- A function can return only 2 values. If more than 2 values needs to be returned, use hash