Skip to content

What it is

RuboCop is a Ruby static code analyser and formatter, enforcing the community style guide with hundreds of configurable cops and autocorrection.

Configure cops in .rubocop.yml. Autocorrect fixes what it safely can, and a todo file freezes existing offences so only new ones fail.

Installation

gem 'rubocop', require: false

Getting started

The smallest useful thing you can do with it, and what each part means.

Configuration and the todo file
# .rubocop.yml
require:
  - rubocop-rails
  - rubocop-rspec
  - rubocop-performance

AllCops:
  NewCops: enable
  TargetRubyVersion: 3.3
  Exclude:
    - 'db/schema.rb'
    - 'vendor/**/*'

Style/Documentation:
  Enabled: false

Metrics/MethodLength:
  Max: 20

inherit_from: .rubocop_todo.yml

# On an existing codebase:
#   bundle exec rubocop --auto-gen-config
# then fix the todo entries incrementally.
Without the todo file, enabling RuboCop on a mature project produces thousands of offences and gets switched off. With it, the ratchet only tightens.

Advanced usage

Where the library earns its place over a simpler alternative.

Autocorrect levels and targeted disabling
# Safe corrections only — will not change behaviour.
bundle exec rubocop -a

# Includes unsafe corrections; review the diff carefully.
bundle exec rubocop -A

# Only files changed in this branch — fast feedback in CI.
bundle exec rubocop --force-exclusion $(git diff --name-only main | grep '\.rb$')

# Inline, with a reason.
# rubocop:disable Metrics/AbcSize -- state machine, splitting hurts clarity
def transition(event)
  # …
end
# rubocop:enable Metrics/AbcSize
The distinction between -a and -A matters: unsafe autocorrections can change behaviour, so they should never be applied without reading the resulting diff.

Errors and fixes

The failures you are most likely to hit, and what actually resolves them.

Thousands of offences on first run
Run --auto-gen-config to create .rubocop_todo.yml, then work through it.
Autocorrect broke the code
An unsafe correction from -A. Review its diff, revert, and disable that specific cop.

Best practices

  • Generate a todo file when adopting on an existing project rather than fixing everything at once.
  • Add the rails, rspec and performance extensions — the performance cops catch real inefficiencies.
  • Use -a in a pre-commit hook and reserve -A for reviewed batches.
  • Always give a reason when disabling a cop inline.

Background

Why it exists, and what it was reacting to.

RuboCop encodes the Ruby Style Guide as executable rules. Its autocorrect and todo-file features make adoption on an existing codebase practical rather than overwhelming.