This cop enforces the use of either #alias or #alias_method
depending on configuration.
It also flags uses of alias :symbol rather than alias bareword.
Examples
EnforcedStyle: prefer_alias (default)
# badalias_method:bar, :fooalias:bar:foo# goodalias bar foo
EnforcedStyle: prefer_alias_method
# badalias:bar:fooalias bar foo
# goodalias_method:bar, :foo
This cop checks for uses of "*" as a substitute for join.
Not all cases can reliably checked, due to Ruby's dynamic
types, so we consider only cases when the first argument is an
array literal or the second is a string literal.
Examples
# bad%w(foo bar baz)*","# good%w(foo bar baz).join(",")
This cop checks for non-ascii (non-English) characters
in comments. You could set an array of allowed non-ascii chars in
AllowedChars attribute (empty by default).
Examples
# bad# Translates from English to 日本語。# good# Translates from English to Japanese
# bad - creates a single attribute accessor (deprecated in Ruby 1.9)attr:something, trueattr:one, :two, :three# behaves as attr_reader# goodattr_accessor:somethingattr_reader:one, :two, :three
Check for uses of braces or do/end around single line or
multi-line blocks.
Examples
EnforcedStyle: line_count_based (default)
# bad - single line block
items.each do |item| item /5end# good - single line block
items.each { |item| item /5 }
# bad - multi-line block
things.map { |thing|
something = thing.some_method
process(something)
}
# good - multi-line block
things.map do |thing|
something = thing.some_method
process(something)
end
EnforcedStyle: semantic
# Prefer `do...end` over `{...}` for procedural blocks.# return value is used/assigned# bad
foo = map do |x|
x
endputs (map do |x|
x
end)
# return value is not used out of scope# good
map do |x|
x
end# Prefer `{...}` over `do...end` for functional blocks.# return value is not used out of scope# bad
each { |x|
x
}
# return value is used/assigned# good
foo = map { |x|
x
}
map { |x|
x
}.inspect
EnforcedStyle: braces_for_chaining
# bad
words.each do |word|
word.flip.flop
end.join("-")
# good
words.each { |word|
word.flip.flop
}.join("-")
This cop checks for braces around the last parameter in a method call
if the last parameter is a hash.
It supports braces, no_braces and context_dependent styles.
Examples
EnforcedStyle: braces
# The `braces` style enforces braces around all method# parameters that are hashes.# bad
some_method(x, y, a:1, b:2)
# good
some_method(x, y, {a:1, b:2})
EnforcedStyle: no_braces (default)
# The `no_braces` style checks that the last parameter doesn't# have braces around it.# bad
some_method(x, y, {a:1, b:2})
# good
some_method(x, y, a:1, b:2)
EnforcedStyle: context_dependent
# The `context_dependent` style checks that the last parameter# doesn't have braces around it, but requires braces if the# second to last parameter is also a hash literal.# bad
some_method(x, y, {a:1, b:2})
some_method(x, y, {a:1, b:2}, a:1, b:2)
# good
some_method(x, y, a:1, b:2)
some_method(x, y, {a:1, b:2}, {a:1, b:2})
Configurable attributes
Name
Default value
Configurable values
EnforcedStyle
no_braces
braces, no_braces, context_dependent
Style/CaseEquality
Enabled by default
Supports autocorrection
Enabled
No
This cop checks for uses of the case equality operator(===).
This cop checks for uses of class variables. Offenses
are signaled only on assignment to class variables to
reduce the number of offenses that would be reported.
You have to be careful when setting a value for a class
variable; if a class has been inherited, changing the
value of a class variable also affects the inheriting
classes. This means that it's almost always better to
use a class instance variable instead.
Examples
# badclassA@@test=10end# goodclassA@test=10endclassAdeftest@@test# you can access class variable without offenseendend
This cop checks that comment annotation keywords are written according
to guidelines.
Examples
# bad# TODO make better# good# TODO: make better# bad# TODO:make better# good# TODO: make better# bad# fixme: does not work# good# FIXME: does not work# bad# Optimize does not work# good# OPTIMIZE: does not work
This cop checks for comments put on the same line as some keywords.
These keywords are: begin, class, def, end, module.
Note that some comments (such as :nodoc: and rubocop:disable) are
allowed.
Examples
# badif condition
statement
end# end if# badclassX# comment
statement
end# baddefx; end# comment# goodif condition
statement
end# goodclassX# :nodoc:
y
end
Style/ConditionalAssignment
Enabled by default
Supports autocorrection
Enabled
Yes
Check for if and case statements where each branch is used for
assignment to the same variable when using the return of the
condition can be used instead.
Examples
EnforcedStyle: assign_to_condition (default)
# badif foo
bar =1else
bar =2endcase foo
when'a'
bar +=1else
bar +=2endif foo
some_method
bar =1else
some_other_method
bar =2end# good
bar =if foo
1else2end
bar +=case foo
when'a'1else2end
bar <<if foo
some_method
1else
some_other_method
2end
EnforcedStyle: assign_inside_condition
# bad
bar =if foo
1else2end
bar +=case foo
when'a'1else2end
bar <<if foo
some_method
1else
some_other_method
2end# goodif foo
bar =1else
bar =2endcase foo
when'a'
bar +=1else
bar +=2endif foo
some_method
bar =1else
some_other_method
bar =2end
Configurable attributes
Name
Default value
Configurable values
EnforcedStyle
assign_to_condition
assign_to_condition, assign_inside_condition
SingleLineConditionsOnly
true
Boolean
IncludeTernaryExpressions
true
Boolean
Style/Copyright
Enabled by default
Supports autocorrection
Disabled
Yes
Check that a copyright notice was given in each source file.
The default regexp for an acceptable copyright notice can be found in
config/default.yml. The default can be changed as follows:
This regex string is treated as an unanchored regex. For each file
that RuboCop scans, a comment that matches this regex must be found or
an offense is reported.
Configurable attributes
Name
Default value
Configurable values
Notice
^Copyright (\(c\) )?2[0-9]{3} .+
String
AutocorrectNotice
``
String
Style/DateTime
Enabled by default
Supports autocorrection
Enabled
No
This cop checks for uses of DateTime that should be replaced by
Date or Time.
Examples
# bad - uses `DateTime` for current timeDateTime.now
# good - uses `Time` for current timeTime.now
# bad - uses `DateTime` for modern dateDateTime.iso8601('2016-06-29')
# good - uses `Date` for modern dateDate.iso8601('2016-06-29')
# good - uses `DateTime` with start argument for historical dateDateTime.iso8601('1751-04-23', Date::ENGLAND)
AllowCoercion: false (default)
# bad - coerces to `DateTime`
something.to_datetime
# good - coerces to `Time`
something.to_time
AllowCoercion: true
# good
something.to_datetime
# good
something.to_time
This cop checks for parentheses in the definition of a method,
that does not take any arguments. Both instance and
class/singleton methods are checked.
Examples
# baddeffoo()
# does a thingend# gooddeffoo# does a thingend# also gooddeffoo() does_a_thing end
# baddefBaz.foo()
# does a thingend# gooddefBaz.foo# does a thingend
This cop checks for places where the #__dir__ method can replace more
complex constructs to retrieve a canonicalized absolute path to the
current file.
Examples
# bad
path =File.expand_path(File.dirname(__FILE__))
# bad
path =File.dirname(File.realpath(__FILE__))
# good
path =__dir__
Style/Documentation
Enabled by default
Supports autocorrection
Enabled
No
This cop checks for missing top-level documentation of
classes and modules. Classes with no body are exempt from the
check and so are namespace modules - modules that have nothing in
their bodies except classes, other modules, or constant definitions.
The documentation requirement is annulled if the class or module has
a "#:nodoc:" comment next to it. Likewise, "#:nodoc: all" does the
same for all its children.
Examples
# badclassPerson# ...end# good# Description/Explanation of Person classclassPerson# ...end
Configurable attributes
Name
Default value
Configurable values
Exclude
spec/**/*, test/**/*
Array
Style/DocumentationMethod
Enabled by default
Supports autocorrection
Disabled
No
This cop checks for missing documentation comment for public methods.
It can optionally be configured to also require documentation for
non-public methods.
This cop checks for uses of double negation (!!) to convert something
to a boolean value. As this is both cryptic and usually redundant, it
should be avoided.
Please, note that when something is a boolean value
!!something and !something.nil? are not the same thing.
As you're unlikely to write code that can accept values of any type
this is rarely a problem in practice.
This cop checks for loops which iterate a constant number of times,
using a Range literal and #each. This can be done more readably using
Integer#times.
This check only applies if the block takes no parameters.
Examples
# bad
(1..5).each { }
# good5.times { }
# bad
(0...10).each {}
# good10.times {}
Style/EachWithObject
Enabled by default
Supports autocorrection
Enabled
Yes
This cop looks for inject / reduce calls where the passed in object is
returned at the end and so could be replaced by each_with_object without
the need to return the object at the end.
However, we can't replace with each_with_object if the accumulator
parameter is assigned to within the block.
Examples
# bad
[1, 2].inject({}) { |a, e| a[e] = e; a }
# good
[1, 2].each_with_object({}) { |e, a| a[e] = e }
Style/EmptyBlockParameter
Enabled by default
Supports autocorrection
Enabled
Yes
This cop checks for pipes for empty block parameters. Pipes for empty
block parameters do not cause syntax errors, but they are redundant.
Examples
# bad
a do ||do_somethingend# bada { ||do_something }
# goodadoend# gooda { do_something }
Style/EmptyCaseCondition
Enabled by default
Supports autocorrection
Enabled
Yes
This cop checks for case statements with an empty condition.
Examples
# bad:casewhen x ==0puts'x is 0'when y ==0puts'y is 0'elseputs'neither is 0'end# good:if x ==0puts'x is 0'elsif y ==0puts'y is 0'elseputs'neither is 0'end# good: (the case condition node is not empty)case n
when0puts'zero'when1puts'one'elseputs'more'end
Style/EmptyElse
Enabled by default
Supports autocorrection
Enabled
Yes
Checks for empty else-clauses, possibly including comments and/or an
explicit nil depending on the EnforcedStyle.
Examples
EnforcedStyle: empty
# warn only on empty else# badif condition
statement
elseend# goodif condition
statement
elsenilend# goodif condition
statement
else
statement
end# goodif condition
statement
end
EnforcedStyle: nil
# warn on else with nil in it# badif condition
statement
elsenilend# goodif condition
statement
elseend# goodif condition
statement
else
statement
end# goodif condition
statement
end
EnforcedStyle: both (default)
# warn on empty else and else with nil in it# badif condition
statement
elsenilend# badif condition
statement
elseend# goodif condition
statement
else
statement
end# goodif condition
statement
end
Configurable attributes
Name
Default value
Configurable values
EnforcedStyle
both
empty, nil, both
Style/EmptyLambdaParameter
Enabled by default
Supports autocorrection
Enabled
Yes
This cop checks for parentheses for empty lambda parameters. Parentheses
for empty lambda parameters do not cause syntax errors, but they are
redundant.
This cop checks for the formatting of empty method definitions.
By default it enforces empty method definitions to go on a single
line (compact style), but it can be configured to enforce the end
to go on its own line (expanded style).
Note: A method definition is not considered empty if it contains
comments.
Examples
EnforcedStyle: compact (default)
# baddeffoo(bar)
enddefself.foo(bar)
end# gooddeffoo(bar); enddeffoo(bar)
# bazenddefself.foo(bar); end
EnforcedStyle: expanded
# baddeffoo(bar); enddefself.foo(bar); end# gooddeffoo(bar)
enddefself.foo(bar)
end
This cop checks eval method usage. eval can receive source location
metadata, that are filename and line number. The metadata is used by
backtraces. This cop recommends to pass the metadata to eval method.
This cop looks for uses of the for keyword, or each method. The
preferred alternative is set in the EnforcedStyle configuration
parameter. An each call with a block on a single line is always
allowed, however.
Examples
EnforcedStyle: each (default)
# baddeffoofor n in [1, 2, 3] doputs n
endend# gooddeffoo
[1, 2, 3].each do |n|
puts n
endend
EnforcedStyle: for
# baddeffoo
[1, 2, 3].each do |n|
puts n
endend# gooddeffoofor n in [1, 2, 3] doputs n
endend
This cop enforces the use of a single string formatting utility.
Valid options include Kernel#format, Kernel#sprintf and String#%.
The detection of String#% cannot be implemented in a reliable
manner for all cases, so only two scenarios are considered -
if the first argument is a string literal and if the second
argument is an array literal.
Use a consistent style for named format string tokens.
Note:unannotated style cop only works for strings
which are passed as arguments to those methods:
sprintf, format, %.
The reason is that unannotated format is very similar
to encoded URLs or Date/Time formatting strings.
This cop is designed to help upgrade to Ruby 3.0. It will add the
comment # frozen_string_literal: true to the top of files to
enable frozen string literals. Frozen string literals may be default
in Ruby 3.0. The comment will be added below a shebang and encoding
comment. The frozen string literal comment is only valid in Ruby 2.3+.
Examples
EnforcedStyle: when_needed (default)
# The `when_needed` style will add the frozen string literal comment# to files only when the `TargetRubyVersion` is set to 2.3+.# badmoduleFoo# ...end# good# frozen_string_literal: truemoduleFoo# ...end
EnforcedStyle: always
# The `always` style will always add the frozen string literal comment# to a file, regardless of the Ruby version or if `freeze` or `<<` are# called on a string literal.# badmoduleBar# ...end# good# frozen_string_literal: truemoduleBar# ...end
EnforcedStyle: never
# The `never` will enforce that the frozen string literal comment does# not exist in a file.# bad# frozen_string_literal: truemoduleBaz# ...end# goodmoduleBaz# ...end
Configurable attributes
Name
Default value
Configurable values
EnforcedStyle
when_needed
when_needed, always, never
Style/GlobalVars
Enabled by default
Supports autocorrection
Enabled
No
This cops looks for uses of global variables.
It does not report offenses for built-in global variables.
Built-in global variables are allowed by default. Additionally
users can allow additional variables via the AllowedVariables option.
Note that backreferences like $1, $2, etc are not global variables.
Examples
# bad$foo=2
bar =$foo+5# goodFOO=2
foo =2$stdin.read
Use a guard clause instead of wrapping the code inside a conditional
expression
Examples
# baddeftestif something
work
endend# gooddeftestreturnunless something
work
end# also gooddeftest
work if something
end# badif something
raise'exception'else
ok
end# goodraise'exception'if something
ok
If the else branch of a conditional consists solely of an if node,
it can be combined with the else to become an elsif.
This helps to keep the nesting level from getting too deep.
Checks for if and unless statements that would fit on one line
if written as a modifier if/unless. The maximum line length is
configured in the Metrics/LineLength cop. The tab size is configured
in the IndentationWidth of the Layout/Tab cop.
Examples
# badif condition
do_stuff(bar)
endunless qux.empty?
Foo.do_something
end# good
do_stuff(bar) if condition
Foo.do_something unless qux.empty?
This cop checks for raise or fail statements which do not specify an
explicit exception class. (This raises a RuntimeError. Some projects
might prefer to use exception classes which more precisely identify the
nature of the error.)
# good
foo.each do |f|
# Standalone comment
f.bar
end# bad
foo.each do |f|
f.bar # Trailing inline commentend
Style/InverseMethods
Enabled by default
Supports autocorrection
Enabled
Yes
This cop check for usages of not (not or !) called on a method
when an inverse of that method can be used instead.
Methods that can be inverted by a not (not or !) should be defined
in InverseMethods
Methods that are inverted by inverting the return
of the block that is passed to the method should be defined in
InverseBlocks
Examples
# bad!foo.none?
!foo.any? { |f| f.even? }
!foo.blank?
!(foo == bar)
foo.select { |f| !f.even? }
foo.reject { |f| f !=7 }
# good
foo.none?
foo.blank?
foo.any? { |f| f.even? }
foo != bar
foo == bar
!!('foo'=~/^\w+$/)
!(foo.class <Numeric) # Checking class hierarchy is allowed
This cop checks for hardcoded IP addresses, which can make code
brittle. IP addresses are likely to need to be changed when code
is deployed to a different server or environment, which may break
a deployment if forgotten. Prefer setting IP addresses in ENV or
other configuration.
Examples
# bad
ip_address ='127.59.241.29'# good
ip_address =ENV['DEPLOYMENT_IP_ADDRESS']
Configurable attributes
Name
Default value
Configurable values
Whitelist
::
Array
Style/Lambda
Enabled by default
Supports autocorrection
Enabled
Yes
This cop (by default) checks for uses of the lambda literal syntax for
single line lambdas, and the method call syntax for multiline lambdas.
It is configurable to enforce one of the styles for both single line
and multiline lambdas as well.
Examples
EnforcedStyle: line_count_dependent (default)
# bad
f =lambda { |x| x }
f =->(x) do
x
end# good
f =->(x) { x }
f =lambdado |x|
x
end
EnforcedStyle: lambda
# bad
f =->(x) { x }
f =->(x) do
x
end# good
f =lambda { |x| x }
f =lambdado |x|
x
end
EnforcedStyle: literal
# bad
f =lambda { |x| x }
f =lambdado |x|
x
end# good
f =->(x) { x }
f =->(x) do
x
end
This cop checks for string literal concatenation at
the end of a line.
Examples
# bad
some_str ='ala'+'bala'
some_str ='ala'<<'bala'# good
some_str ='ala' \
'bala'
Style/MethodCallWithArgsParentheses
Enabled by default
Supports autocorrection
Disabled
Yes
This cop checks presence of parentheses in method calls containing
parameters. By default, macro methods are ignored. Additional methods
can be added to the IgnoredMethods list.
Examples
# bad
array.delete e
# good
array.delete(e)
# good# Operators don't need parens
foo == bar
# good# Setter methods don't need parens
foo.bar = baz
# okay with `puts` listed in `IgnoredMethods`puts'test'# IgnoreMacros: true (default)# goodclassFoo
bar :bazend# IgnoreMacros: false# badclassFoo
bar :bazend
This cop checks for methods called on a do...end block. The point of
this check is that it's easy to miss the call tacked on to the block
when reading code.
This cop checks for potential uses of Enumerable#minmax.
Examples
# bad
bar = [foo.min, foo.max]
return foo.min, foo.max
# good
bar = foo.minmax
return foo.minmax
Style/MissingElse
Enabled by default
Supports autocorrection
Disabled
No
Checks for if expressions that do not have an else branch.
Supported styles are: if, case, both.
Examples
EnforcedStyle: if
# warn when an `if` expression is missing an `else` branch.# badif condition
statement
end# goodif condition
statement
else# the content of `else` branch will be determined by Style/EmptyElseend# goodcase var
when condition
statement
end# goodcase var
when condition
statement
else# the content of `else` branch will be determined by Style/EmptyElseend
EnforcedStyle: case
# warn when a `case` expression is missing an `else` branch.# badcase var
when condition
statement
end# goodcase var
when condition
statement
else# the content of `else` branch will be determined by Style/EmptyElseend# goodif condition
statement
end# goodif condition
statement
else# the content of `else` branch will be determined by Style/EmptyElseend
EnforcedStyle: both (default)
# warn when an `if` or `case` expression is missing an `else` branch.# badif condition
statement
end# badcase var
when condition
statement
end# goodif condition
statement
else# the content of `else` branch will be determined by Style/EmptyElseend# goodcase var
when condition
statement
else# the content of `else` branch will be determined by Style/EmptyElseend
Configurable attributes
Name
Default value
Configurable values
EnforcedStyle
both
if, case, both
Style/MissingRespondToMissing
Enabled by default
Supports autocorrection
Enabled
No
This cop checks for the presence of method_missing without also
defining respond_to_missing?.
This cop checks for grouping of mixins in class and module bodies.
By default it enforces mixins to be placed in separate declarations,
but it can be configured to enforce grouping them in one declaration.
This cop checks that include, extend and prepend statements appear
inside classes and modules, not at the top level, so as to not affect
the behavior of Object.
Use next to skip iteration instead of a condition at the end.
Examples
EnforcedStyle: skip_modifier_ifs (default)
# bad
[1, 2].each do |a|
if a ==1puts a
endend# good
[1, 2].each do |a|
nextunless a ==1puts a
end# good
[1, 2].each do |o|
puts o unless o ==1end
EnforcedStyle: always
# With `always` all conditions at the end of an iteration needs to be# replaced by next - with `skip_modifier_ifs` the modifier if like# this one are ignored: `[1, 2].each { |a| return 'yes' if a == 1 }`# bad
[1, 2].each do |o|
puts o unless o ==1end# bad
[1, 2].each do |a|
if a ==1puts a
endend# good
[1, 2].each do |a|
nextunless a ==1puts a
end
This cop checks for non-nil checks, which are usually redundant.
Non-nil checks are allowed if they are the final nodes of predicate.
good
def signed_in?
!current_user.nil?
end
Examples
# badif x !=nilend# good (when not allowing semantic changes)# bad (when allowing semantic changes)if!x.nil?
end# good (when allowing semantic changes)if x
end
This cop checks for octal, hex, binary and decimal literals using
uppercase prefixes and corrects them to lowercase prefix
or no prefix (in case of decimals).
Examples
EnforcedOctalStyle: zero_with_o (default)
# bad - missing octal prefix
num =01234# bad - uppercase prefix
num =0O1234
num =0X12AB
num =0B10101# bad - redundant decimal prefix
num =0D1234
num =0d1234# good
num =0o1234
num =0x12AB
num =0b10101
num =1234
This cop checks for usage of comparison operators (==,
>, <) to test numbers as zero, positive, or negative.
These can be replaced by their respective predicate methods.
The cop can also be configured to do the reverse.
The cop disregards #nonzero? as it its value is truthy or falsey,
but not true and false, and thus not always interchangeable with
!= 0.
The cop ignores comparisons to global variables, since they are often
populated with objects which can be compared with integers, but are
not themselves Integer polymorphic.
Examples
EnforcedStyle: predicate (default)
# bad
foo ==00> foo
bar.baz >0# good
foo.zero?
foo.negative?
bar.baz.positive?
EnforcedStyle: comparison
# bad
foo.zero?
foo.negative?
bar.baz.positive?
# good
foo ==00> foo
bar.baz >0
This cop checks for potential usage of the ||= operator.
Examples
# bad
name = name ? name : 'Bozhidar'# bad
name =if name
name
else'Bozhidar'end# badunless name
name ='Bozhidar'end# bad
name ='Bozhidar'unless name
# good - set name to 'Bozhidar', only if it's nil or false
name ||='Bozhidar'
Checks for simple usages of parallel assignment.
This will only complain when the number of variables
being assigned matched the number of assigning variables.
Examples
# bad
a, b, c =1, 2, 3
a, b, c = [1, 2, 3]
# good
one, two =*foo
a, b = foo()
a, b = b, a
a =1
b =2
c =3
This cop enforces the consistent usage of %-literal delimiters.
Specify the 'default' key to set all preferred delimiters at once. You
can continue to specify individual preferred delimiters to override the
default.
This cop checks for usage of the %Q() syntax when %q() would do.
Examples
EnforcedStyle: lower_case_q (default)
# The `lower_case_q` style prefers `%q` unless# interpolation is needed.# bad%Q[Mix the foo into the baz.]%Q(They all said: 'Hooray!')# good%q[Mix the foo into the baz]%q(They all said: 'Hooray!')
EnforcedStyle: upper_case_q
# The `upper_case_q` style requires the sole use of `%Q`.# bad%q/Mix the foo into the baz./%q{They all said: 'Hooray!'}# good%Q/Mix the foo into the baz./%Q{They all said: 'Hooray!'}
Configurable attributes
Name
Default value
Configurable values
EnforcedStyle
lower_case_q
lower_case_q, upper_case_q
Style/PerlBackrefs
Enabled by default
Supports autocorrection
Enabled
Yes
This cop looks for uses of Perl-style regexp match
backreferences like $1, $2, etc.
This cop (by default) checks for uses of methods Hash#has_key? and
Hash#has_value? where it enforces Hash#key? and Hash#value?
It is configurable to enforce the inverse, using verbose method
names also.
This cop checks the args passed to fail and raise. For exploded
style (default), it recommends passing the exception class and message
to raise, rather than construct an instance of the error. It will
still allow passing just a message, or the construction of an error
with more than one argument.
The exploded style works identically, but with the addition that it
will also suggest constructing error objects when the exception is
passed multiple arguments.
This cop checks for the use of randomly generated numbers,
added/subtracted with integer literals, as well as those with
Integer#succ and Integer#pred methods. Prefer using ranges instead,
as it clearly states the intentions.
# baddefredundantbegin
ala
bala
rescueStandardError => e
something
endend# gooddefpreferred
ala
bala
rescueStandardError => e
something
end# bad# When using Ruby 2.5 or later.
do_something dobegin
something
rescue => ex
anything
endend# good# In Ruby 2.5 or later, you can omit `begin` in `do-end` block.
do_something do
something
rescue => ex
anything
end# good# Stabby lambdas don't support implicit `begin` in `do-end` blocks.->dobegin
foo
rescueBar
baz
endend
This cop check for uses of Object#freeze on immutable objects.
Examples
# badCONST=1.freeze
# goodCONST=1
Style/RedundantParentheses
Enabled by default
Supports autocorrection
Enabled
Yes
This cop checks for redundant parentheses.
Examples
# bad
(x) if ((y.z).nil?)
# good
x if y.z.nil?
Style/RedundantReturn
Enabled by default
Supports autocorrection
Enabled
Yes
This cop checks for redundant return expressions.
Examples
# These bad cases should be extended to handle methods whose body is# if/else or a case expression with a default branch.# baddeftestreturn something
end# baddeftest
one
two
three
return something
end# gooddeftestreturn something if something_else
end# gooddeftestif x
elsif y
elseendend
Sending a message to same object with zero arguments in
presence of a method name clash with an argument or a local
variable.
Calling an attribute writer to prevent an local variable assignment.
Note, with using explicit self you can only send messages with public or
protected scope, you cannot send private messages this way.
Note we allow uses of self with operators because it would be awkward
otherwise.
Examples
# baddeffoo(bar)
self.baz
end# gooddeffoo(bar)
self.bar # Resolves name clash with the argument.enddeffoo
bar =1self.bar # Resolves name clash with the local variable.enddeffoo%w[x y z].selectdo |bar|
self.bar == bar # Resolves name clash with argument of the block.endend
This cop checks for rescuing StandardError. There are two supported
styles implicit and explicit. This cop will not register an offense
if any error other than StandardError is specified.
Examples
EnforcedStyle: implicit
# `implicit` will enforce using `rescue` instead of# `rescue StandardError`.# badbegin
foo
rescueStandardError
bar
end# goodbegin
foo
rescue
bar
end# goodbegin
foo
rescueOtherError
bar
end# goodbegin
foo
rescueStandardError, SecurityError
bar
end
EnforcedStyle: explicit (default)
# `explicit` will enforce using `rescue StandardError`# instead of `rescue`.# badbegin
foo
rescue
bar
end# goodbegin
foo
rescueStandardError
bar
end# goodbegin
foo
rescueOtherError
bar
end# goodbegin
foo
rescueStandardError, SecurityError
bar
end
Configurable attributes
Name
Default value
Configurable values
EnforcedStyle
explicit
implicit, explicit
Style/ReturnNil
Enabled by default
Supports autocorrection
Disabled
Yes
This cop enforces consistency between 'return nil' and 'return'.
Supported styles are: return, return_nil.
Examples
EnforcedStyle: return (default)
# baddeffoo(arg)
returnnilif arg
end# gooddeffoo(arg)
returnif arg
end
EnforcedStyle: return_nil
# baddeffoo(arg)
returnif arg
end# gooddeffoo(arg)
returnnilif arg
end
Configurable attributes
Name
Default value
Configurable values
EnforcedStyle
return
return, return_nil
Style/SafeNavigation
Enabled by default
Supports autocorrection
Enabled
Yes
This cop transforms usages of a method call safeguarded by a non nil
check for the variable whose method is being called to
safe navigation (&.). If there is a method chain, all of the methods
in the chain need to be checked for safety, and all of the methods will
need to be changed to use safe navigation. We have limited the cop to
not register an offense for method chains that exceed 2 methods.
Configuration option: ConvertCodeThatCanStartToReturnNil
The default for this is false. When configured to true, this will
check for code in the format !foo.nil? && foo.bar. As it is written,
the return of this code is limited to false and whatever the return
of the method is. If this is converted to safe navigation,
foo&.bar can start returning nil as well as what the method
returns.
Examples
# bad
foo.bar if foo
foo.bar.baz if foo
foo.bar(param1, param2) if foo
foo.bar { |e| e.something } if foo
foo.bar(param) { |e| e.something } if foo
foo.bar if!foo.nil?
foo.bar unless!foo
foo.bar unless foo.nil?
foo && foo.bar
foo && foo.bar.baz
foo && foo.bar(param1, param2)
foo && foo.bar { |e| e.something }
foo && foo.bar(param) { |e| e.something }
# good
foo&.bar
foo&.bar&.baz
foo&.bar(param1, param2)
foo&.bar { |e| e.something }
foo&.bar(param) { |e| e.something }
foo && foo.bar.baz.qux # method chain with more than 2 methods
foo && foo.nil? # method that `nil` responds to# Method calls that do not use `.`
foo && foo < bar
foo < bar if foo
# This could start returning `nil` as well as the return of the method
foo.nil? || foo.bar
!foo || foo.bar
# Methods that are used on assignment, arithmetic operation or# comparison should not be converted to use safe navigation
foo.baz = bar if foo
foo.baz + bar if foo
foo.bar >2if foo
Configurable attributes
Name
Default value
Configurable values
ConvertCodeThatCanStartToReturnNil
false
Boolean
Whitelist
present?, blank?, presence, try, try!
Array
Style/SelfAssignment
Enabled by default
Supports autocorrection
Enabled
Yes
This cop enforces the use the shorthand for self-assignment.
# The `only_raise` style enforces the sole use of `raise`.# badbeginfailrescueException# handle itenddefwatch_outfailrescueException# handle itendKernel.fail# goodbeginraiserescueException# handle itenddefwatch_outraiserescueException# handle itendKernel.raise
EnforcedStyle: only_fail
# The `only_fail` style enforces the sole use of `fail`.# badbeginraiserescueException# handle itenddefwatch_outraiserescueException# handle itendKernel.raise# goodbeginfailrescueException# handle itenddefwatch_outfailrescueException# handle itendKernel.fail
EnforcedStyle: semantic
# The `semantic` style enforces the use of `fail` to signal an# exception, then will use `raise` to trigger an offense after# it has been rescued.# badbeginraiserescueException# handle itenddefwatch_out# Error thrownrescueExceptionfailendKernel.failKernel.raise# goodbeginfailrescueException# handle itenddefwatch_outfailrescueExceptionraise'Preferably with descriptive message'end
explicit_receiver.fail
explicit_receiver.raise
This cop checks whether the block parameters of a single-line
method accepting a block match the names specified via configuration.
For instance one can configure reduce(inject) to use |a, e| as
parameters.
Configuration option: Methods
Should be set to use this cop. Array of hashes, where each key is the
method name and value - array of argument names.
Examples
Methods: [{reduce: %w[a b]}]
# bad
foo.reduce { |c, d| c + d }
foo.reduce { |_, _d| 1 }
# good
foo.reduce { |a, b| a + b }
foo.reduce { |a, _b| a }
foo.reduce { |a, (id, _)| a + id }
foo.reduce { true }
# good
foo.reduce do |c, d|
c + d
end
This cop looks for uses of Perl-style global variables.
Examples
EnforcedStyle: use_english_names (default)
# goodputs$LOAD_PATHputs$LOADED_FEATURESputs$PROGRAM_NAMEputs$ERROR_INFOputs$ERROR_POSITIONputs$FIELD_SEPARATOR# or $FSputs$OUTPUT_FIELD_SEPARATOR# or $OFSputs$INPUT_RECORD_SEPARATOR# or $RSputs$OUTPUT_RECORD_SEPARATOR# or $ORSputs$INPUT_LINE_NUMBER# or $NRputs$LAST_READ_LINEputs$DEFAULT_OUTPUTputs$DEFAULT_INPUTputs$PROCESS_ID# or $PIDputs$CHILD_STATUSputs$LAST_MATCH_INFOputs$IGNORECASEputs$ARGV# or ARGVputs$MATCHputs$PREMATCHputs$POSTMATCHputs$LAST_PAREN_MATCH
This cop identifies places where $stderr.puts can be replaced by
warn. The latter has the advantage of easily being disabled by,
e.g. the -W0 interpreter flag, or setting $VERBOSE to nil.
Checks if uses of quotes match the configured preference.
Examples
EnforcedStyle: single_quotes (default)
# bad"No special symbols""No string interpolation""Just text"# good'No special symbols''No string interpolation''Just text'"Wait! What's #{this}!"
EnforcedStyle: double_quotes
# bad'Just some text''No special chars or interpolation'# good"Just some text""No special chars or interpolation""Every string in #{project} uses double_quotes"
This cop can check for array literals made up of symbols that are not
using the %i() syntax.
Alternatively, it checks for symbol arrays using the %i() syntax on
projects which do not want to use that syntax.
Configuration option: MinSize
If set, arrays with fewer elements than this value will not trigger the
cop. For example, a MinSize of3` will not enforce a style on an array
of 2 or fewer elements.
# bad
something.map { |s| s.upcase }
# good
something.map(&:upcase)
Configurable attributes
Name
Default value
Configurable values
IgnoredMethods
respond_to, define_method
Array
Style/TernaryParentheses
Enabled by default
Supports autocorrection
Enabled
Yes
This cop checks for the presence of parentheses around ternary
conditions. It is configurable to enforce inclusion or omission of
parentheses using EnforcedStyle. Omission is only enforced when
removing the parentheses won't cause a different behavior.
Examples
EnforcedStyle: require_no_parentheses (default)
# bad
foo = (bar?) ? a : b
foo = (bar.baz?) ? a : b
foo = (bar && baz) ? a : b
# good
foo = bar? ? a : b
foo = bar.baz? ? a : b
foo = bar && baz ? a : b
EnforcedStyle: require_parentheses
# bad
foo = bar? ? a : b
foo = bar.baz? ? a : b
foo = bar && baz ? a : b
# good
foo = (bar?) ? a : b
foo = (bar.baz?) ? a : b
foo = (bar && baz) ? a : b
EnforcedStyle: require_parentheses_when_complex
# bad
foo = (bar?) ? a : b
foo = (bar.baz?) ? a : b
foo = bar && baz ? a : b
# good
foo = bar? ? a : b
foo = bar.baz? ? a : b
foo = (bar && baz) ? a : b
This cop checks for trailing comma in hash literals.
Examples
EnforcedStyleForMultiline: consistent_comma
# bad
a = { foo:1, bar:2, }
# good
a = {
foo:1, bar:2,
qux:3,
}
# good
a = {
foo:1,
bar:2,
}
EnforcedStyleForMultiline: comma
# bad
a = { foo:1, bar:2, }
# good
a = {
foo:1,
bar:2,
}
EnforcedStyleForMultiline: no_comma (default)
# bad
a = { foo:1, bar:2, }
# good
a = {
foo:1,
bar:2
}
Configurable attributes
Name
Default value
Configurable values
EnforcedStyleForMultiline
no_comma
comma, consistent_comma, no_comma
Style/TrailingMethodEndStatement
Enabled by default
Supports autocorrection
Enabled
Yes
This cop checks for trailing code after the method definition.
Examples
# baddefsome_method
do_stuff; enddefdo_this(x)
baz.map { |b| b.this(x) } enddeffoo
block do
bar
endend# gooddefsome_method
do_stuff
enddefdo_this(x)
baz.map { |b| b.this(x) }
enddeffoo
block do
bar
endend
Style/TrailingUnderscoreVariable
Enabled by default
Supports autocorrection
Enabled
Yes
This cop checks for extra underscores in variable assignment.
Examples
# bad
a, b, _= foo()
a, b, _, = foo()
a, _, _= foo()
a, _, _, = foo()
# good
a, b, = foo()
a, = foo()
*a, b, _= foo()
# => We need to know to not include 2 variables in a
a, *b, _= foo()
# => The correction `a, *b, = foo()` is a syntax error# good if AllowNamedUnderscoreVariables is true
a, b, _something= foo()
Configurable attributes
Name
Default value
Configurable values
AllowNamedUnderscoreVariables
true
Boolean
Style/TrivialAccessors
Enabled by default
Supports autocorrection
Enabled
Yes
This cop looks for trivial reader/writer methods, that could
have been created with the attr_* family of functions automatically.
Examples
# baddeffoo@fooenddefbar=(val)
@bar= val
enddefself.baz@bazend# goodattr_reader:fooattr_writer:barclass<< selfattr_reader:bazend
This cop checks for usage of the %W() syntax when %w() would do.
Examples
# bad%W(cat dog pig)%W[door wall floor]# good%w/swim run bike/%w[shirt pants shoes]%W(apple #{fruit} grape)
Style/UnneededCondition
Enabled by default
Supports autocorrection
Enabled
Yes
This cop checks for unnecessary conditional expressions.
Examples
# bad
a = b ? b : c
# good
a = b || c
# badif b
b
else
c
end# good
b || c
# goodif b
b
elsif cond
c
end
Style/UnneededInterpolation
Enabled by default
Supports autocorrection
Enabled
Yes
This cop checks for strings that are just an interpolated expression.
Examples
# bad"#{@var}"# good@var.to_s
# good if @var is already a String@var
Style/UnneededPercentQ
Enabled by default
Supports autocorrection
Enabled
Yes
This cop checks for usage of the %q/%Q syntax when '' or "" would do.
Examples
# bad
name =%q(Bruce Wayne)
time =%q(8 o'clock)
question =%q("What did you say?")# good
name ='Bruce Wayne'
time ="8 o'clock"
question ='"What did you say?"'
Checks for while and until statements that would fit on one line
if written as a modifier while/until. The maximum line length is
configured in the Metrics/LineLength cop.
This cop can check for array literals made up of word-like
strings, that are not using the %w() syntax.
Alternatively, it can check for uses of the %w() syntax, in projects
which do not want to include that syntax.
Configuration option: MinSize
If set, arrays with fewer elements than this value will not trigger the
cop. For example, a MinSize of 3 will not enforce a style on an
array of 2 or fewer elements.
This cop checks for Yoda conditions, i.e. comparison operations where
readability is reduced because the operands are not ordered the same
way as they would be ordered in spoken English.
Examples
EnforcedStyle: all_comparison_operators (default)
# bad99== foo
"bar"!= foo
42>= foo
10< bar
# good
foo ==99
foo =="bar"
foo <=42
bar >10
EnforcedStyle: equality_operators_only
# bad99== foo
"bar"!= foo
# good99>= foo
3< a && a <5
This cop checks for numeric comparisons that can be replaced
by a predicate method, such as receiver.length == 0,
receiver.length > 0, receiver.length != 0,
receiver.length < 1 and receiver.size == 0 that can be
replaced by receiver.empty? and !receiver.empty.