Skip to content
Tutorials Center
My learning

Topics

Lesson 107 of 134 ยท Testing and Tooling

Style and Linting

Learn Ruby naming and formatting conventions, idiomatic style choices, what RuboCop checks and how to configure it, and build a small linter yourself with the Prism parser.

Two programs can do exactly the same thing and still feel very different to read. One uses snake_case names, short methods, early returns and the right iterator; the other mixes styles, indents by whim and loops with a counter. Ruby has a strong tradition of readable code, and a community style guide that describes the shared conventions. A linter is a program that reads your source and points out places where it departs from those conventions or looks like a bug. The linter everyone uses in Ruby is RuboCop.

This lesson covers the conventions first, because you need them whether or not a tool enforces them, then RuboCop and its configuration, and finally a small linter we build ourselves. RuboCop is a third-party gem and is not installed on our runner (require 'rubocop' raises a LoadError), so RuboCop usage is read-only here. Everything that touches the Ruby language itself, such as the parser we use for our own linter, runs for real.

Why bother with style?

Style rules are not about taste. They exist so that:

  • Code reads the same everywhere. When every project names methods and indents blocks the same way, you can read an unfamiliar codebase quickly.
  • Reviews stay about substance. A tool settles "tabs or spaces" so that people can discuss design.
  • Common bugs are caught early. A linter flags unused variables, shadowed names, duplicated hash keys and unreachable code.
  • Diffs stay small. Formatting a file the same way each time avoids noisy changes.

The most important rule is the first one in any team: be consistent. If a codebase has its own rules, follow them even when you would choose differently.

Naming conventions

Ruby uses the shape of a name to tell you what it is. This is not only a habit; the language enforces a few of them (a constant must start with a capital letter).

Kind Convention Example
Local variables, methods, arguments snake_case user_name, total_price
Classes and modules CamelCase (also called PascalCase) ShoppingCart, Comparable
Constants SCREAMING_SNAKE_CASE MAX_RETRIES
Predicate methods (return true/false) end in ? empty?, valid?
Dangerous or mutating methods end in !, with a safer twin without it sort / sort!
Unused variables start with _ _index, _
Files snake_case.rb, named after the class shopping_cart.rb

A few more small points: never start a method name with get_ or set_ (Ruby uses name and name=), and do not name a predicate is_valid?; write valid?.

Ruby Naming conventions are enforced by Ruby in places

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Notice what the style gives you. full? and empty? read like questions, and an add that returns true or false is easy to use in a condition. For the bang/non-bang pair, see Methods.

Formatting conventions

The guide's layout rules are short enough to memorize:

  • Two spaces per indentation level, never tabs.
  • Keep lines to about 80 to 120 characters. Many teams settle on 100 or 120 today.
  • No trailing whitespace; end the file with one newline.
  • One blank line between method definitions; no blank line right after def or right before end.
  • Spaces around operators and after commas: a + b, [1, 2, 3]. No space inside parentheses or brackets: foo(bar), not foo( bar ).
  • Hash literals: { name: "Ada", age: 36 } with spaces inside the braces, and the key: shorthand when the variable has the same name ({ name:, age: }).
  • Use do ... end for multi-line blocks and { ... } for single-line ones.
  • Omit return at the end of a method (the last expression is the result), but use it for early exits at the top.

Idiomatic Ruby: say it the Ruby way

Style is also about choosing the construct that Ruby programmers expect. The next example shows the same behavior twice: first in a clumsy style, then in an idiomatic one. Both parts print the same lines, so you can compare them directly.

Ruby The same program, in two styles

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The idiomatic version drops the manual counter and push, uses map to transform a list, even? instead of % 2 == 0, &. (the safe-navigation operator) to skip nil, and the implicit last expression instead of return. See Ternary and safe navigation and Iterators.

Some other habits experienced Rubyists share:

  • Guard clauses over nesting. Handle the unusual case at the top and return, so the main logic is not indented three levels deep.
  • unless for a simple negative; never unless ... else. unless reads well with one short condition, and gets confusing with elsif or else.
  • each, map, select instead of for. The for loop leaks its variable into the surrounding scope.
  • %w[a b c] and %i[a b c] for lists of words and symbols.
  • Symbols and keyword arguments for options: connect(host: "x", timeout: 5) instead of positional booleans.
  • Prefer Struct or Data over a hash when the keys are fixed (see Structs and Data).
  • Never rescue Exception; rescue StandardError or a specific class (see Exceptions).
  • Avoid monkey patching core classes in application code unless a refinement is enough (see Refinements).
  • Pick one quote style (single quotes unless you interpolate, or double quotes everywhere) and let the linter enforce it.

The frozen string literal comment

Many Ruby files start with this magic comment:

Ruby
# frozen_string_literal: true

It makes every plain string literal in that file frozen, so mutation raises an error. It saves memory (identical literals can share one object) and catches accidental changes. Ruby 3.4 and later print a warning when you mutate a literal in a file without the comment, and plan to make literals frozen by default one day. Let us see the comment at work. Because the comment must be the first line of the file, it is the first line of this example:

Ruby The frozen_string_literal comment (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The program prints true, RUBY, and ruby 4.0, then fails on the last mutation with can't modify frozen String: "ruby" (FrozenError). The fixes are to build a new string (name + " rocks"), to start from +"" or String.new, or to call dup. For more, read Frozen and immutable objects.

RuboCop

RuboCop is a linter and code formatter for Ruby, and the de facto standard. It reads your files and reports offenses, grouped into departments:

  • Layout: indentation, spacing, line length, trailing whitespace.
  • Lint: probable bugs, such as an unused variable, a duplicate method definition, or a useless assignment.
  • Style: idioms, such as preferring unless over if !, or map over a manual loop.
  • Naming: the conventions in the table above.
  • Metrics: method length, class length and complexity.
  • Security and Performance: for example Kernel#eval or select.first instead of find.

It is a gem, so you add it to a Gemfile (see RubyGems and Bundler) and run it from the terminal. This is a read-only example, because the gem is not available on our runner:

Terminal
# read-only example: needs the rubocop gem
bundle add rubocop --group development
bundle exec rubocop                      # check the whole project
bundle exec rubocop app/models/user.rb   # check one file
bundle exec rubocop -a                   # safely auto-correct what it can
bundle exec rubocop -A                   # also apply "unsafe" corrections (review the diff!)
bundle exec rubocop --auto-gen-config    # record all current offenses in a TODO file

A report looks like this (read-only, shortened):

TEXT
app/models/user.rb:12:5: C: Style/GuardClause: Use a guard clause instead of wrapping the code inside a conditional expression.
app/models/user.rb:20:80: C: Layout/LineLength: Line is too long. [112/100]
app/models/user.rb:31:7: W: Lint/UselessAssignment: Useless assignment to variable - `total`.

3 files inspected, 3 offenses detected, 2 offenses autocorrectable

The letter after the position is the severity: Convention, Warning, Error, Fatal. The name Style/GuardClause is the cop that fired; you use that name in configuration.

Configuring it

RuboCop reads a .rubocop.yml file in the project root. The usual workflow is to start from the defaults, adjust the few rules your team disagrees with, and commit the file:

YAML
# read-only example: .rubocop.yml
AllCops:
  TargetRubyVersion: 4.0
  NewCops: enable
  Exclude:
    - "db/schema.rb"
    - "vendor/**/*"

Layout/LineLength:
  Max: 120

Style/StringLiterals:
  EnforcedStyle: double_quotes

Metrics/MethodLength:
  Max: 15

Style/Documentation:
  Enabled: false

You can silence a rule for one line or a block with a comment, which is better than disabling it globally when the exception is rare:

Ruby
# read-only example
def legacy_name # rubocop:disable Naming/PredicateName
  true
end

For an existing project with hundreds of offenses, use --auto-gen-config. It writes a .rubocop_todo.yml that disables the failing cops for the files that currently fail, so new code is held to the standard while old code is cleaned up gradually. Run RuboCop in CI so that a pull request cannot add new offenses, and in your editor so you get feedback as you type. Many teams use the standard gem (or its Ruby wrapper) as an alternative: it is a fixed, no-debate RuboCop configuration.

Do not treat metrics cops as law. A method that is 16 lines long is not worse than one with 15. Use the numbers as a nudge to look at the code and ask "is this doing two things?"

Build a tiny linter with Prism

A linter does not need to be mysterious. Ruby 4.0 ships the Prism parser, which turns source text into a tree of nodes you can walk. With that we can check naming conventions in about twenty lines. Our checker flags method names that are not snake_case and lines that are too long, and shows how a syntax error is reported.

Ruby A small naming linter built on Prism

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

A visitor is an object whose visit_*_node methods Prism calls as it walks the tree. We override visit_def_node, check the name, and call super so the walk continues into nested nodes. RuboCop works on the same principle with hundreds of such checks (each cop is a small visitor) plus a formatter. Note that Ruby itself already rejects some mistakes at parse time, which our lint reports as a syntax error before any style check runs.

A workflow that works

  1. Agree on a style with your team and write it into .rubocop.yml (or adopt standard).
  2. Turn on format-on-save in your editor, so Layout offenses never reach a commit.
  3. Run the linter in CI. Fail the build on new offenses.
  4. When a cop is wrong for a specific line, disable it narrowly and write why.
  5. Review the intent of style rules from time to time. If the team keeps disabling a cop, change the rule.

Linters check form, not meaning. They cannot tell you that your algorithm is wrong, which is the job of the tests in Minitest, but they catch a lot of small mistakes cheaply.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which names follow Ruby conventions for a method and a constant?

    Methods and variables use snake_case; constants use SCREAMING_SNAKE_CASE. Classes and modules use CamelCase.
  2. 2. What does # frozen_string_literal: true at the top of a file do?

    String literals in the file become frozen. You build a new string, or use +"", dup or String.new, when you need a changeable one.
  3. 3. Which style is preferred for the check 'is this list empty?'

    The predicate method empty? is the idiomatic, most readable choice and exists on arrays, hashes, strings and more.
  4. 4. What is the best way to deal with 800 existing offenses when adding RuboCop to an old project?

    The generated .rubocop_todo.yml holds the existing offenses aside, so new code is held to the standard while old code improves step by step.
  5. 5. In the Prism linter, why does the overridden visit_def_node call super?

    The default visit method walks the children. Without super, a def nested inside this one would never be checked.

Summary

  • Ruby style is a set of shared conventions: snake_case for methods and variables, CamelCase for classes, SCREAMING_SNAKE_CASE for constants, ? for predicates and ! for dangerous methods.
  • Format with two-space indentation, no trailing whitespace and short lines; prefer guard clauses, iterators like map and each, &. and early returns over manual loops and nesting.
  • # frozen_string_literal: true freezes literals in a file; mutating one raises FrozenError.
  • RuboCop is a third-party linter and formatter configured by .rubocop.yml; it groups checks into Layout, Lint, Style, Naming, Metrics and more, and can auto-correct many offenses.
  • A linter is a program that walks a parse tree; with Ruby's built-in Prism parser you can write small checks yourself.
  • Be consistent, automate the rules in your editor and CI, and spend human review time on design.

Next: Performance Tips