# good - space after { and before }
{ one: 1, two: 2 }
# good - no space after { and before }
{one: 1, two: 2}
# bad
def some_method(arg1=:default, arg2=nil, arg3=[])
# do something...
end
# good
def some_method(arg1 = :default, arg2 = nil, arg3 = [])
# do something...
end
Two options
# bad - need to consult first line to
# understand second line
one.two.three.
four
# good - it's immediately clear what's
# going on the second line
one.two.three
.four
# bad - need to read ahead to the second line
# to know that the chain continues
one.two.three
.four
# good - it's immediately clear that the
# expression continues beyond the first line
one.two.three.
four
# bad
SomeClass::some_method
some_object::some_method
# good
SomeClass.some_method
some_object.some_method
SomeModule::SomeClass::SOME_CONST
SomeModule::SomeClass()
# bad
def some_method()
# body omitted
end
# good
def some_method
# body omitted
end
# bad
def some_method_with_parameters param1, param2
# body omitted
end
# good
def some_method_with_parameters(param1, param2)
# body omitted
end
# bad
if condition
result = x
else
result = y
end
# good
result =
if condition
x
else
y
end
# bad
if some_condition
do_something
end
# good
do_something if some_condition
# another good option
some_condition && do_something
# bad
unless success?
puts 'failure'
else
puts 'success'
end
# good
if success?
puts 'success'
else
puts 'failure'
end
# bad
user.set({ name: 'John', age: 45, permissions: { read: true } })
# good
user.set(name: 'John', age: 45, permissions: { read: true })
# bad
Kernel.exit!()
2.even?()
fork()
'test'.upcase()
# good
Kernel.exit!
2.even?
fork
'test'.upcase
# bad
array.delete hash.fetch :foo
# good
array.delete(hash.fetch(:foo))
# bad
result = calculate array, start_point, steps
# good
result = calculate(array, start_point, steps)
# bad (+ a warning)
if v = array.grep(/foo/)
do_something(v)
...
end
# good (MRI would still complain, but RuboCop won't)
if (v = array.grep(/foo/))
do_something(v)
...
end
# good
v = array.grep(/foo/)
if v
do_something(v)
...
end
class Person
# extend and include go first
extend SomeModule
include AnotherModule
# inner classes
CustomErrorKlass = Class.new(StandardError)
# constants are next
SOME_CONSTANT = 20
# afterwards we have attribute macros
attr_reader :name
# followed by other macros (if any)
validates :name
# public class methods are next in line
def self.some_method
end
# followed by public instance methods
def some_method
end
# protected and private methods are grouped near the end
protected
def some_protected_method
end
private
def some_private_method
end
end
# bad
validates_presence_of :email
# good
validates :email, presence: true