Coding conventions
suggest changeRuby lets you write the same thing in many ways: with or without parentheses, with if or unless, with { } or do ... end. The community has settled on a common style, written down in the Ruby Style Guide and enforced by RuboCop and Standard. Following it makes your code look familiar to every Ruby programmer, and it ends arguments about formatting in code review.
This article covers the conventions that matter most in everyday code: layout, naming, methods, conditionals, blocks, strings, hashes, classes, exceptions and comments. At the end it shows how to check them automatically. All examples were run with Ruby 4.0 and RuboCop 1.92.
Layout
- Indent with 2 spaces. Never use tabs.
- Keep lines short. RuboCop's default limit is 120 characters, and many teams use 80 or 100.
- Use UTF-8 source files with Unix line endings (
\n) and a newline at the end of the file. Don't leave trailing whitespace. - Put one blank line between method definitions, and an empty line after a block of guard clauses.
- Put spaces around operators, after commas and around
=. Don't put spaces inside( )or[ ]. - Start every file with the
# frozen_string_literal: truemagic comment (see the Strings section below).
# frozen_string_literal: true
def area(width, height)
width * height
end
def perimeter(width, height)
2 * (width + height)
end
sizes = [[3, 4], [5, 6]]
areas = sizes.map { |w, h| area(w, h) }
p areas
p perimeter(3, 4)
[12, 30]
14
Naming
| What | Convention | Example |
|---|---|---|
| Local variables, methods, method arguments | snake_case |
unit_price, add_item |
| Instance and class variables | @snake_case |
@line_items |
| Classes and modules | CamelCase |
InvoiceItem, Billing |
| Other constants | SCREAMING_SNAKE_CASE |
MAX_RETRIES |
| Files and directories | snake_case of the class |
billing/invoice_item.rb |
| Predicate methods (return true/false) | end with ? |
empty?, free? |
| Setter methods | end with = |
quantity= |
| "Dangerous" variant of a method | end with ! |
uniq!, save! |
| Unused variables | start with _ |
_key, _ |
# frozen_string_literal: true
module Billing
TAX_RATE = 0.2
class InvoiceItem
attr_reader :name, :unit_price, :quantity
def initialize(name, unit_price:, quantity: 1)
@name = name
@unit_price = unit_price
@quantity = quantity
end
def total = unit_price * quantity
def free? = unit_price.zero?
def quantity=(value)
raise ArgumentError, "quantity must be positive" unless value.positive?
@quantity = value
end
def to_s = "#{name} x#{quantity}"
end
end
item = Billing::InvoiceItem.new("Pen", unit_price: 250)
item.quantity = 4
puts item
p item.total
p item.free?
begin
item.quantity = 0
rescue ArgumentError => e
puts "error: #{e.message}"
end
Pen x4
1000
false
error: quantity must be positive
Some naming rules that are easy to get wrong:
- No
get_,set_oris_prefixes. Writename,name=andactive?, notget_name,set_nameandis_active. Theattr_reader,attr_writerandattr_accessormacros generate exactly these names. - A
?method returns a boolean. It shouldn't need arguments in most cases, and it shouldn't change state. !means "more dangerous than the method without!", not "mutates". It only makes sense when both versions exist:uniqreturns a new array anduniq!changes the receiver in place. In Rails,savereturnsfalseon failure whilesave!raises. Many methods that mutate have no!at all (Array#push,Hash#delete,String#<<).- Acronyms. The style guide writes them in upper case (
HTTPClient), but the Zeitwerk autoloader used by Rails maps the filehttp_client.rbtoHttpClient. In a Rails or Zeitwerk project, follow the file name rule, or configure an inflection. - Use conversion method names that Ruby already knows:
to_s,to_a,to_h,to_proc.putsand string interpolation callto_sfor you.
The bang versions of the built-in methods return nil when nothing changed, so don't chain them:
# frozen_string_literal: true
tags = %w[ruby go ruby]
p tags.uniq
p tags
p tags.uniq!
p tags
p tags.uniq!
["ruby", "go"]
["ruby", "go", "ruby"]
["ruby", "go"]
["ruby", "go"]
nil
A leading underscore tells the reader (and ruby -w) that a variable is unused on purpose. A bare _ works too:
# frozen_string_literal: true
prices = { pen: 250, pad: 400, ink: 900 }
prices.each.with_index(1) { |(name, _cents), i| puts "#{i}. #{name}" }
first, *_rest = prices.keys
p first
_, second_price = prices.to_a[1]
p second_price
1. pen
2. pad
3. ink
:pen
400
Methods
- Use parentheses around parameters in a
defwhen there are any. Omit them when there are none:def total, notdef total(). - When calling a method, use parentheses around the arguments. Leave them out for methods with no arguments and for methods used like keywords:
puts,p,raise,require,include,attr_reader,private, and DSL calls in Rake or RSpec. - Don't write
returnon the last line. A method returns the value of its last expression. Usereturnonly to exit early. - Use an endless method (
def total = ..., Ruby 3.0+) only for a short method with a single expression. - Keep methods short. RuboCop's default limit is 10 lines. If a method needs comments to explain its parts, split it into smaller methods with good names.
- Use keyword arguments for booleans and for options. A call like
export(rows, "out.csv", true, false)can't be understood without looking up the method:
# frozen_string_literal: true
# Avoid: positional booleans are unreadable at the call site
def export_v1(rows, path, overwrite, header)
"#{rows.size} rows -> #{path} overwrite=#{overwrite} header=#{header}"
end
# Prefer: keyword arguments with defaults
def export(rows, path:, overwrite: false, header: true)
"#{rows.size} rows -> #{path} overwrite=#{overwrite} header=#{header}"
end
rows = [[1, "a"], [2, "b"]]
puts export_v1(rows, "out.csv", true, false)
puts export(rows, path: "out.csv", overwrite: true)
2 rows -> out.csv overwrite=true header=false
2 rows -> out.csv overwrite=true header=true
See Keyword arguments for required keywords and **options.
Conditionals
Handle special cases first with guard clauses, then write the main case without nesting:
# frozen_string_literal: true
User = Data.define(:name, :email, :active)
# Nested conditionals push the real work to the right
def welcome_nested(user)
if user
if user.active
if user.email.include?("@")
"Welcome, #{user.name}"
else
"invalid email"
end
else
"inactive"
end
else
"no user"
end
end
# Guard clauses handle the special cases first and return early
def welcome(user)
return "no user" unless user
return "inactive" unless user.active
return "invalid email" unless user.email.include?("@")
"Welcome, #{user.name}"
end
ann = User.new(name: "Ann", email: "ann@example.com", active: true)
bob = User.new(name: "Bob", email: "bob", active: true)
[ann, bob, nil].each do |u|
puts "#{welcome_nested(u)} | #{welcome(u)}"
end
Welcome, Ann | Welcome, Ann
invalid email | invalid email
no user | no user
Other rules for conditionals:
- Use the modifier form (
do_this if condition) when the body is a single short line. - Use
unlessfor a negative condition, but never withelseand never with a negated condition (unless !x). Rewrite those asif. - Use the ternary operator
? :only for simple expressions, and never nest it. - Use
!,&&and||for logic.not,andandorhave very low precedence, see Common pitfalls. ifandcaseare expressions, so assign their result instead of assigning a variable in every branch.- Use
case/whenwith ranges and classes instead of longif/elsifchains, andcase/into match the structure of hashes and arrays. - Don't compare with
true,falseornil(if x == true,if x.nil? == false). Everything exceptnilandfalseis truthy.
# frozen_string_literal: true
def status_label(code)
case code
when 200..299 then "ok"
when 404 then "not found"
when 500.. then "server error"
else "other"
end
end
def describe(response)
case response
in { status: 200, body: String => body }
"ok: #{body}"
in { status: 301 | 302, location: }
"redirect to #{location}"
in { status: }
"status #{status}"
end
end
[204, 404, 503, 302].each { |c| print status_label(c), " " }
puts
puts describe({ status: 200, body: "hi" })
puts describe({ status: 302, location: "/login" })
puts describe({ status: 418 })
stock = 0
label = stock.zero? ? "sold out" : "#{stock} left"
puts label
puts "restock needed" if stock < 5
puts "all good" unless stock < 5
level =
if stock > 100
:high
elsif stock > 10
:medium
else
:low
end
p level
ok not found server error other
ok: hi
redirect to /login
status 418
sold out
restock needed
:low
Blocks and collections
- Use
{ ... }for single-line blocks anddo ... endfor multi-line blocks. - Use
&:methodwhen the block just calls one method on its argument. - Inside a short block,
it(Ruby 3.4+) can stand for the single block parameter. Give the parameter a name when the block is longer than one line. - Prefer the method that says what you compute (
map,select,filter_map,sum,count,each_with_object,group_by) overeachwith a manual accumulator. - Break long chains into one call per line, with the dot at the start of each line.
# frozen_string_literal: true
orders = [
{ id: 1, customer: "ann", total: 120, paid: true },
{ id: 2, customer: "bob", total: 80, paid: false },
{ id: 3, customer: "ann", total: 45, paid: true },
]
# Avoid: manual accumulation with each
paid_totals = []
orders.each do |order|
paid_totals << order[:total] if order[:paid]
end
p paid_totals
# Prefer: say what you compute
paid_totals = orders.filter_map { |o| o[:total] if o[:paid] }
p paid_totals
revenue = orders.sum { it[:total] }
p revenue
customers = orders.map { it[:customer] }.uniq
p customers
unpaid = orders.count { !it[:paid] }
p unpaid
# Symbol to proc for a single method call
p %w[ann bob].map(&:capitalize)
# do...end for multi-line blocks
by_customer = orders.each_with_object(Hash.new(0)) do |order, totals|
totals[order[:customer]] += order[:total]
end
p by_customer
# Long chains: one call per line, leading dot
report =
orders
.select { it[:paid] }
.sort_by { -it[:total] }
.map { "##{it[:id]} #{it[:total]}" }
p report
[120, 45]
[120, 45]
245
["ann", "bob"]
1
["Ann", "Bob"]
{"ann" => 165, "bob" => 80}
["#1 120", "#3 45"]
Notice the trailing comma after the last element of the multi-line orders array. Many teams require it (RuboCop's consistent_comma style, see the configuration below), because then adding an element changes only one line in the diff. RuboCop's default is no trailing comma. Choose one style and use it everywhere.
Strings
- Pick one quote style and stay with it. RuboCop's default is single quotes unless you need interpolation or escapes. Standard (and many projects, including this book) uses double quotes everywhere, so a string doesn't need to change when you add interpolation later.
- Use interpolation, not
+withto_s. - Use
formatwith named references (%<name>s) for padding and number formatting. - Use the squiggly heredoc
<<~for multi-line text. It removes the common indentation. - Use
%w[]for arrays of words and%i[]for arrays of symbols.
# frozen_string_literal: true
name = "Ann"
count = 3
# Avoid: concatenation and to_s
puts "Hello " + name + ", you have " + count.to_s + " messages"
# Prefer: interpolation
puts "Hello #{name}, you have #{count} messages"
# format for alignment and number formatting
puts format("%<name>-6s|%<amount>8.2f|", name:, amount: 1234.5)
# Squiggly heredoc strips the common indentation
def usage
<<~TEXT
Usage: report [options] FILE
-v verbose output
TEXT
end
puts usage
# Word and symbol arrays
p %w[draft published archived]
p %i[read write admin]
# Build strings with << on an unfrozen copy (+"" or String.new)
csv = +""
[[1, "pen"], [2, "pad"]].each { |id, item| csv << "#{id},#{item}\n" }
print csv
Hello Ann, you have 3 messages
Hello Ann, you have 3 messages
Ann | 1234.50|
Usage: report [options] FILE
-v verbose output
["draft", "published", "archived"]
[:read, :write, :admin]
1,pen
2,pad
With # frozen_string_literal: true, every string literal in the file is frozen. Modifying one raises FrozenError instead of silently changing a string that may be shared, and Ruby can reuse the same object instead of allocating a new one each time. When you need a mutable string, start with +"" or String.new. Since Ruby 3.4, literals in files without the comment are "chilled": they can still be modified, but you get a warning with ruby -W, because literals will be frozen by default in a future version. See Immutability.
Hashes
- Use symbols for keys you control, with the
key: valuesyntax. Use=>only for keys that aren't symbols, such as strings from JSON. - Use the shorthand
{ host:, port: }(Ruby 3.1+) when local variables have the same names as the keys. - Use
fetchwhen a key must be present.[]returnsnilfor a missing key, and the error shows up far from its cause.
# frozen_string_literal: true
# Symbol keys with the key: value syntax
config = { host: "localhost", port: 5432 }
# Hash shorthand (Ruby 3.1+) when the variable has the key's name
host = "db.internal"
port = 6432
p({ host:, port: })
# String keys (e.g. parsed JSON) need =>
headers = { "Content-Type" => "text/plain", "X-Request-Id" => "abc" }
p headers.keys
# fetch fails loudly on a missing key; [] silently returns nil
p config[:timeout]
p config.fetch(:timeout, 30)
begin
config.fetch(:timeout)
rescue KeyError => e
puts e.message
end
{host: "db.internal", port: 6432}
["Content-Type", "X-Request-Id"]
nil
30
key not found: :timeout
Classes and modules
Lay out the body of a class in a fixed order, so readers know where to look:
extendandinclude- constants, nested classes and error classes
attr_readerand other macros- class methods (
def self.name) initialize- public instance methods
protected, thenprivatemethods
Other conventions:
- Use
attr_readerinstead of writing trivial getter methods. Add writers only when callers really need to change the value. - Write
privateonce on its own line and put all private methods below it, indented at the same level as the other methods. - Define class methods with
def self.name. Useclass << selfonly when you have many of them or needprivateclass methods. - Use
Data.definefor small immutable value objects andStructwhen you need mutation, instead of hashes with fixed keys. - Don't use class variables (
@@count), because they're shared with all subclasses. Use a class-level instance variable or a constant instead. - Put one class per file, in a file named after the class.
# frozen_string_literal: true
require "forwardable"
class Playlist
extend Forwardable
include Enumerable
MAX_SONGS = 100
Song = Data.define(:title, :seconds)
class Full < StandardError; end
attr_reader :name
def_delegators :@songs, :size, :empty?
def self.from_titles(name, titles)
new(name).tap do |list|
titles.each { list.add(it, seconds: 180) }
end
end
def initialize(name)
@name = name
@songs = []
end
def add(title, seconds:)
raise Full, "#{name} already has #{MAX_SONGS} songs" if size >= MAX_SONGS
@songs << Song.new(title:, seconds:)
self
end
def each(&) = @songs.each(&)
def duration = format_time(sum(&:seconds))
def to_s = "#{name} (#{size} songs, #{duration})"
private
def format_time(seconds)
min, sec = seconds.divmod(60)
format("%<min>d:%<sec>02d", min:, sec:)
end
end
list = Playlist.from_titles("Road trip", %w[Drive Highway])
list.add("Exit", seconds: 95)
puts list
p list.map(&:title)
p list.max_by(&:seconds)
begin
list.format_time(10)
rescue NoMethodError => e
puts e.message
end
Road trip (3 songs, 7:35)
["Drive", "Highway", "Exit"]
#<data Playlist::Song title="Drive", seconds=180>
private method 'format_time' called for an instance of Playlist
Defining each and including Enumerable gives the class map, sum, max_by and about 50 other methods. That's more idiomatic than exposing the internal array.
Exceptions
- Raise with the class and message as two arguments:
raise ArgumentError, "bad value", notraise ArgumentError.new("bad value"). - Give a library or a subsystem its own base error class that inherits from
StandardError, and derive specific errors from it. Callers can then rescue one error or all of them. - Rescue the most specific class you can handle. Never write
rescue Exception, which also catchesInterrupt(Ctrl+C) andSystemExit. - In a method, use a method-level
rescueinstead of wrapping the whole body inbegin ... end. - Don't use exceptions for normal control flow. If a missing value is normal, return
nilor usefetchwith a default.
# frozen_string_literal: true
module Payments
class Error < StandardError; end
class CardDeclined < Error; end
class InvalidAmount < Error
def initialize(amount)
super("amount must be positive, got #{amount}")
end
end
def self.charge(amount, card:)
raise InvalidAmount, amount unless amount.positive?
raise CardDeclined, "card #{card} was declined" if card.end_with?("0000")
"charged #{amount}"
end
end
# Method-level rescue: no extra begin/end needed
def checkout(amount, card)
Payments.charge(amount, card:)
rescue Payments::CardDeclined => e
"try another card (#{e.message})"
rescue Payments::Error => e
"payment failed: #{e.message}"
end
puts checkout(100, "4242")
puts checkout(100, "1230000")
puts checkout(-5, "4242")
charged 100
try another card (card 1230000 was declined)
payment failed: amount must be positive, got -5
Comments
Good code with good names needs few comments. Write comments that explain why something is done, not what the next line does. Document the public methods of a library with a comment directly above the def. Many projects use YARD tags (@param, @return) so that documentation can be generated:
# frozen_string_literal: true
# Splits +total+ cents into +parts+ amounts that differ by at most one cent.
# The first amounts get the extra cents, so the sum always equals +total+.
#
# @param total [Integer] amount in cents
# @param parts [Integer] number of shares, must be positive
# @return [Array<Integer>]
#
# split_evenly(100, 3) # => [34, 33, 33]
def split_evenly(total, parts)
base, extra = total.divmod(parts)
# Integer division, not floats: 0.1 + 0.2 != 0.3 in binary floating point.
Array.new(parts) { |i| i < extra ? base + 1 : base }
end
p split_evenly(100, 3)
p split_evenly(10, 4).sum
[34, 33, 33]
10
Use # comments even for long text. =begin/=end block comments exist but are rarely used. Delete commented-out code, because version control remembers it. Mark unfinished work with TODO: or FIXME: followed by a note, so tools can find it. See Comments for the syntax.
Enforcing conventions with RuboCop
Don't check style by hand in code review. RuboCop is the standard linter and formatter for Ruby. Its rules are called cops, grouped into departments such as Layout, Naming, Style, Lint (likely bugs) and Metrics (method length, complexity). Add it to the Gemfile:
group :development do
gem "rubocop", require: false
end
Configure it in .rubocop.yml in the project root. This configuration was used to check the examples in this article. Apart from the deliberately bad "avoid" code, they pass with no offenses:
AllCops:
TargetRubyVersion: 3.4
NewCops: enable
Style/Documentation:
Enabled: false
Style/StringLiterals:
EnforcedStyle: double_quotes
Style/TrailingCommaInArrayLiteral:
EnforcedStyleForMultiline: consistent_comma
Style/TrailingCommaInHashLiteral:
EnforcedStyleForMultiline: consistent_comma
# the default is native, which means CRLF on Windows
Layout/EndOfLine:
EnforcedStyle: lf
NewCops: enable turns on cops added in new RuboCop versions. Without it, RuboCop prints a long list of new cops you haven't configured yet. Style/Documentation requires a comment above every class, which is too strict for most applications.
Here is a file that breaks many conventions:
class Cart
def initialize(); @Items = []; end
def addItem(item)
@Items.push(item)
return self
end
def isEmpty
if not @Items.any? then true else false end
end
def total
sum = 0
@Items.each do |i| sum += i[:price] end
return sum
end
end
cart = Cart.new
cart.addItem({:name => "pen", :price => 3})
puts "total: " + cart.total.to_s
$ bundle exec rubocop messy.rb
Inspecting 1 file
C
Offenses:
messy.rb:1:1: C: [Correctable] Style/FrozenStringLiteralComment: Missing frozen string literal comment.
messy.rb:2:3: C: [Correctable] Style/SingleLineMethods: Avoid single-line method definitions.
messy.rb:2:17: C: [Correctable] Style/DefWithParentheses: Omit the parentheses in defs when the method doesn't accept any arguments.
messy.rb:2:21: C: Naming/VariableName: Use snake_case for variable names.
messy.rb:4:7: C: Naming/MethodName: Use snake_case for method names.
messy.rb:6:5: C: [Correctable] Style/RedundantReturn: Redundant return detected.
messy.rb:9:7: C: Naming/MethodName: Use snake_case for method names.
messy.rb:9:7: C: Naming/PredicateMethod: Predicate method names should end with ?.
messy.rb:10:5: C: [Correctable] Style/NegatedIfElseCondition: Invert the negated condition and swap the if-else branches.
messy.rb:10:5: C: [Correctable] Style/OneLineConditional: Favor the ternary operator (?:) over single-line if/then/else/end constructs.
messy.rb:10:8: C: [Correctable] Style/InverseMethods: Use none? instead of inverting any?.
messy.rb:10:8: C: [Correctable] Style/Not: Use ! instead of not.
messy.rb:15:5: C: [Correctable] Style/SingleLineDoEndBlock: Prefer multiline do...end block.
messy.rb:15:17: C: [Correctable] Style/BlockDelimiters: Prefer {...} over do...end for single-line blocks.
messy.rb:16:5: C: [Correctable] Style/RedundantReturn: Redundant return detected.
messy.rb:21:14: C: [Correctable] Layout/SpaceInsideHashLiteralBraces: Space inside { missing.
messy.rb:21:15: C: [Correctable] Style/HashSyntax: Use the new Ruby 1.9 hash syntax.
messy.rb:21:31: C: [Correctable] Style/HashSyntax: Use the new Ruby 1.9 hash syntax.
messy.rb:21:42: C: [Correctable] Layout/SpaceInsideHashLiteralBraces: Space inside } missing.
messy.rb:22:6: C: [Correctable] Style/StringConcatenation: Prefer string interpolation to string concatenation.
1 file inspected, 20 offenses detected, 16 offenses autocorrectable
(Each offense is also followed by the source line and a ^^^ marker, removed here to save space.)
RuboCop fixes the [Correctable] offenses itself:
rubocop -aapplies only safe corrections, which can't change what the program does.rubocop -Aalso applies unsafe ones. For example, it changes"total: " + cart.total.to_sto interpolation and adds the frozen string literal comment, which would break code that mutates literals. Run your tests and review the diff after-A.
After rubocop -A, the naming offenses remain, because renaming a method would break its callers. Here is the file fixed by hand, which passes with no offenses:
# frozen_string_literal: true
class Cart
def initialize
@items = []
end
def add_item(item)
@items << item
self
end
def empty? = @items.empty?
def total = @items.sum { it[:price] }
end
cart = Cart.new
cart.add_item({ name: "pen", price: 3 })
p cart.empty?
puts "total: #{cart.total}"
$ bundle exec rubocop cart.rb
Inspecting 1 file
.
1 file inspected, no offenses detected
$ ruby cart.rb
false
total: 3
Useful RuboCop practices:
- Adopt it gradually in an existing project.
rubocop --auto-gen-configwrites a.rubocop_todo.ymlthat disables every cop that currently fails. Commit it, then fix the cops one by one. - Disable a cop for one line only when you have a good reason, and say what it is:
def legacy_report # rubocop:disable Metrics/MethodLength -- generated table, splitting hurts readability
- Run it in your editor through the Ruby LSP extension, so offenses show up as you type and files are formatted on save.
- Run it in CI so code that breaks the conventions can't be merged.
rubocopexits with a non-zero status when it finds offenses. See Testing in CI. - Use plugins for frameworks:
rubocop-rails,rubocop-rspec,rubocop-performance,rubocop-minitest.
Standard
If you don't want to configure anything, use Standard (the standard gem). It's built on RuboCop with a fixed set of rules that can't be changed, much like gofmt for Go or Prettier for JavaScript. Its style differs from RuboCop's defaults in a few places: double quotes, no spaces inside hash braces ({name: "pen"}), and no Metrics cops. Run standardrb to check and standardrb --fix to correct.
The choice between the two matters less than using one of them on every commit. Consistent code is easier to read than code in your favourite style.
Summary
- 2-space indentation,
snake_casefor methods and variables,CamelCasefor classes,SCREAMING_SNAKE_CASEfor constants. ?for predicates,=for setters,!only for the dangerous twin of a safe method.- Guard clauses instead of nesting, no explicit
returnat the end, keyword arguments for options. { }for one-line blocks,do ... endfor multi-line, and collection methods instead of manual loops.- Interpolation instead of
+,# frozen_string_literal: truein every file,fetchfor required keys. - A fixed class layout,
privatemethods at the bottom, custom errors that inherit fromStandardError. - Let RuboCop or Standard check all of it automatically.