Coding conventions

suggest change

Ruby 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

# 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:

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

# 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:

# 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

# 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

# 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

# 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:

  1. extend and include
  2. constants, nested classes and error classes
  3. attr_reader and other macros
  4. class methods (def self.name)
  5. initialize
  6. public instance methods
  7. protected, then private methods

Other conventions:

# 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

# 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:

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:

def legacy_report # rubocop:disable Metrics/MethodLength -- generated table, splitting hurts readability

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents