In autocorrect mode, RuboCop will try to automatically fix offenses.
There are three autocorrect modes:
| Flag | Description |
|---|---|
<code>-a</code> / <code>--autocorrect</code> |
Safe corrections only — won’t change code semantics. |
<code>-A</code> / <code>--autocorrect-all</code> |
All corrections, including unsafe ones that may change semantics. |
<code>-x</code> / <code>--fix-layout</code> |
Layout (formatting) corrections only — never changes logic. |
|
Tip
|
Always review the diff and run your test suite after autocorrecting, especially when using <code>-A</code>. |
Safe vs. unsafe
RuboCop distinguishes between safe and unsafe cops and autocorrections:
-
Safe (
true/false) — indicates whether the cop can yield false positives by design. -
SafeAutoCorrect (
true/false) — indicates whether the autocorrection preserves code semantics. If a cop itself is unsafe, its autocorrect is automatically considered unsafe as well.
When you run <code>rubocop -a</code>, cops and autocorrections marked as unsafe are skipped. When you run <code>rubocop -A</code>, everything is applied.
|
Note
|
Some cops may not yet be annotated for safety. Eventually, the safety of each cop will be specified in the default configuration. |
Example: unsafe cop
class Miner
def dig(how_deep)
# ...
end
end
{Miner.new}.dig(42) # => Style/SingleArgumentDig
# => Use Miner.new[] instead of dig
This is the wrong diagnostic; this (contrived) use of dig is not an issue,
and there might not be an alternative. This cop is marked as <code>Safe: false</code>.
Example: safe cop with unsafe autocorrect
# example.rb:
str = 'hello' # => Missing magic comment <code># frozen_string_literal: true</code>
str << 'world'
# autocorrects to:
# frozen_string_literal: true
str = 'hello'
str << 'world' # => now fails because {str} is frozen
# must be manually corrected to:
# frozen_string_literal: true
str = +'hello' # => We want an unfrozen string literal here...
str << 'world' # => ok
This diagnostic is valid since the magic comment is indeed missing (thus Safe: true),
but the autocorrection is not; some string literals need to be prefixed with + to avoid
having them frozen.
Disabling uncorrectable offenses
$ rubocop --autocorrect --disable-uncorrectable
The <code>--disable-uncorrectable</code> flag generates <code># rubocop:todo</code> comments in the code to suppress reporting of offenses that could not be corrected automatically. This is useful for gradually adopting new cops.
Configuring autocorrect per cop
Individual cops can have their autocorrect behavior configured in <code>.rubocop.yml</code>.
See AutoCorrect for the
available settings: always, contextual, and disabled.