Introduction

Role models are important.

— Officer Alex J. Murphy / RoboCop

This Ruby style guide recommends best practices so that real-world Ruby programmers can write code that can be maintained by other real-world Ruby programmers. A style guide that reflects real-world usage gets used, while a style guide that holds to an ideal that has been rejected by the people it is supposed to help risks not getting used at all - no matter how good it is.

The guide is separated into several sections of related guidelines. We’ve tried to add the rationale behind the guidelines (if it’s omitted we’ve assumed it’s pretty obvious).

We didn’t come up with all the guidelines out of nowhere - they are mostly based on the professional experience of the editors, feedback and suggestions from members of the Ruby community and various highly regarded Ruby programming resources, such as "Programming Ruby" and "The Ruby Programming Language".

This style guide evolves over time as additional conventions are identified and past conventions are rendered obsolete by changes in Ruby itself.

Tip

If you’re into Rails or RSpec you might want to check out the complementary Ruby on Rails Style Guide and RSpec Style Guide.

Tip
RuboCop is a static code analyzer (linter) and formatter, based on this style guide.

Guiding Principles

Programs must be written for people to read, and only incidentally for machines to execute.

— Harold Abelson
Structure and Interpretation of Computer Programs

It’s common knowledge that code is read much more often than it is written. The guidelines provided here are intended to improve the readability of code and make it consistent across the wide spectrum of Ruby code. They are also meant to reflect real-world usage of Ruby instead of a random ideal. When we had to choose between a very established practice and a subjectively better alternative we’ve opted to recommend the established practice.[1]

There are some areas in which there is no clear consensus in the Ruby community regarding a particular style (like string literal quoting, spacing inside hash literals, dot position in multi-line method chaining, etc.). In such scenarios all popular styles are acknowledged and it’s up to you to pick one and apply it consistently.

Ruby had existed for over 15 years by the time the guide was created, and the language’s flexibility and lack of common standards have contributed to the creation of numerous styles for just about everything. Rallying people around the cause of community standards took a lot of time and energy, and we still have a lot of ground to cover.

Ruby is famously optimized for programmer happiness. We’d like to believe that this guide is going to help you optimize for maximum programmer happiness.

A Note about Consistency

A foolish consistency is the hobgoblin of little minds, adored by little statesmen and philosophers and divines.

— Ralph Waldo Emerson

A style guide is about consistency. Consistency with this style guide is important. Consistency within a project is more important. Consistency within one class or method is the most important.

However, know when to be inconsistent — sometimes style guide recommendations just aren’t applicable. When in doubt, use your best judgment. Look at other examples and decide what looks best. And don’t hesitate to ask!

In particular: do not break backwards compatibility just to comply with this guide!

Some other good reasons to ignore a particular guideline:

  • When applying the guideline would make the code less readable, even for someone who is used to reading code that follows this style guide.

  • To be consistent with surrounding code that also breaks it (maybe for historic reasons) — although this is also an opportunity to clean up someone else’s mess (in true XP style).

  • Because the code in question predates the introduction of the guideline and there is no other reason to be modifying that code.

  • When the code needs to remain compatible with older versions of Ruby that don’t support the feature recommended by the style guide.

Translations

Translations of the guide are available in the following languages:

Note
These translations are not maintained by our editor team, so their quality and level of completeness may vary. The translated versions of the guide often lag behind the upstream English version.

Source Code Layout

Nearly everybody is convinced that every style but their own is ugly and unreadable. Leave out the "but their own" and they’re probably right…​

— Jerry Coffin (on indentation)

Source Encoding

Use UTF-8 as the source file encoding.

Tip
UTF-8 has been the default source file encoding since Ruby 2.0.

Tabs or Spaces?

Use only spaces for indentation. No hard tabs.

Indentation

Use two spaces per indentation level (aka soft tabs).

# bad - four spaces
def some_method
    do_something
end

# good
def some_method
  do_something
end

Maximum Line Length

Limit lines to 80 characters.

Tip
Most editors and IDEs have configuration options to help you with that. They would typically highlight lines that exceed the length limit.
Why Bother with 80 characters in a World of Modern Widescreen Displays?

A lot of people these days feel that a maximum line length of 80 characters is just a remnant of the past and makes little sense today. After all - modern displays can easily fit 200+ characters on a single line. Still, there are some important benefits to be gained from sticking to shorter lines of code.

First, and foremost - numerous studies have shown that humans read much faster vertically and very long lines of text impede the reading process. As noted earlier, one of the guiding principles of this style guide is to optimize the code we write for human consumption.

Additionally, limiting the required editor window width makes it possible to have several files open side-by-side, and works well when using code review tools that present the two versions in adjacent columns.

The default wrapping in most tools disrupts the visual structure of the code, making it more difficult to understand. The limits are chosen to avoid wrapping in editors with the window width set to 80, even if the tool places a marker glyph in the final column when wrapping lines. Some web based tools may not offer dynamic line wrapping at all.

Some teams strongly prefer a longer line length. For code maintained exclusively or primarily by a team that can reach agreement on this issue, it is okay to increase the line length limit up to 100 characters, or all the way up to 120 characters. Please, restrain the urge to go beyond 120 characters.

No Trailing Whitespace

Avoid trailing whitespace.

Tip
Most editors and IDEs have configuration options to visualize trailing whitespace and to remove it automatically on save.

Line Endings

Use Unix-style line endings.[2]

Tip

If you’re using Git you might want to add the following configuration setting to protect your project from Windows line endings creeping in:

$ git config --global core.autocrlf true

Should I Terminate Files with a Newline?

End each file with a newline.

Tip
This should be done via editor configuration, not manually.

Should I Terminate Expressions with ;?

Don’t use ; to terminate statements and expressions.

# bad
puts 'foobar'; # superfluous semicolon

# good
puts 'foobar'

One Expression Per Line

Use one expression per line.

# bad
puts 'foo'; puts 'bar' # two expressions on the same line

# good
puts 'foo'
puts 'bar'

puts 'foo', 'bar' # this applies to puts in particular

Operator Method Call

Avoid dot where not required for operator method calls.

# bad
num.+ 42

# good
num + 42

Spaces and Operators

Use spaces around operators, after commas, colons and semicolons. Whitespace might be (mostly) irrelevant to the Ruby interpreter, but its proper use is the key to writing easily readable code.

# bad
sum=1+2
a,b=1,2
class FooError<StandardError;end

# good
sum = 1 + 2
a, b = 1, 2
class FooError < StandardError; end

There are a few exceptions:

  • Exponent operator:

# bad
e = M * c ** 2

# good
e = M * c**2
  • Slash in rational literals:

# bad
o_scale = 1 / 48r

# good
o_scale = 1/48r
  • Safe navigation operator:

# bad
foo &. bar
foo &.bar
foo&. bar

# good
foo&.bar

Safe navigation

Avoid long chains of &.. The longer the chain is, the harder it becomes to track what on it could be returning a nil. Replace with . and an explicit check. E.g. if users are guaranteed to have an address and addresses are guaranteed to have a zip code:

# bad
user&.address&.zip&.upcase

# good
user && user.address.zip.upcase

If such a change introduces excessive conditional logic, consider other approaches, such as delegation:

# bad
user && user.address && user.address.zip && user.address.zip.upcase

# good
class User
  def zip
    address&.zip
  end
end
user&.zip&.upcase

Spaces and Braces

No spaces after (, [ or before ], ). Use spaces around { and before }.

# bad
some( arg ).other
[ 1, 2, 3 ].each{|e| puts e}

# good
some(arg).other
[1, 2, 3].each { |e| puts e }

{ and } deserve a bit of clarification, since they are used for block and hash literals, as well as string interpolation.

For hash literals two styles are considered acceptable. The first variant is slightly more readable (and arguably more popular in the Ruby community in general). The second variant has the advantage of adding visual difference between block and hash literals. Whichever one you pick - apply it consistently.

# good - space after { and before }
{ one: 1, two: 2 }

# good - no space after { and before }
{one: 1, two: 2}

With interpolated expressions, there should be no padded-spacing inside the braces.

# bad
"From: #{ user.first_name }, #{ user.last_name }"

# good
"From: #{user.first_name}, #{user.last_name}"

No Space after Bang

No space after !.

# bad
! something

# good
!something

No Space inside Range Literals

No space inside range literals.

# bad
1 .. 3
'a' ... 'z'

# good
1..3
'a'...'z'

Indent when to case

Indent when as deep as case.

# bad
case
  when song.name == 'Misty'
    puts 'Not again!'
  when song.duration > 120
    puts 'Too long!'
  when Time.now.hour > 21
    puts "It's too late"
  else
    song.play
end

# good
case
when song.name == 'Misty'
  puts 'Not again!'
when song.duration > 120
  puts 'Too long!'
when Time.now.hour > 21
  puts "It's too late"
else
  song.play
end
A Bit of History

This is the style established in both "The Ruby Programming Language" and "Programming Ruby". Historically it is derived from the fact that case and switch statements are not blocks, hence should not be indented, and the when and else keywords are labels (compiled in the C language, they are literally labels for JMP calls).

Indent Conditional Assignment

When assigning the result of a conditional expression to a variable, preserve the usual alignment of its branches.

# bad - pretty convoluted
kind = case year
when 1850..1889 then 'Blues'
when 1890..1909 then 'Ragtime'
when 1910..1929 then 'New Orleans Jazz'
when 1930..1939 then 'Swing'
when 1940..1950 then 'Bebop'
else 'Jazz'
end

result = if some_cond
  calc_something
else
  calc_something_else
end

# good - it's apparent what's going on
kind = case year
       when 1850..1889 then 'Blues'
       when 1890..1909 then 'Ragtime'
       when 1910..1929 then 'New Orleans Jazz'
       when 1930..1939 then 'Swing'
       when 1940..1950 then 'Bebop'
       else 'Jazz'
       end

result = if some_cond
           calc_something
         else
           calc_something_else
         end

# good (and a bit more width efficient)
kind =
  case year
  when 1850..1889 then 'Blues'
  when 1890..1909 then 'Ragtime'
  when 1910..1929 then 'New Orleans Jazz'
  when 1930..1939 then 'Swing'
  when 1940..1950 then 'Bebop'
  else 'Jazz'
  end

result =
  if some_cond
    calc_something
  else
    calc_something_else
  end

Empty Lines between Methods

Use empty lines between method definitions and also to break up methods into logical paragraphs internally.

# bad
def some_method
  data = initialize(options)
  data.manipulate!
  data.result
end
def some_other_method
  result
end

# good
def some_method
  data = initialize(options)

  data.manipulate!

  data.result
end

def some_other_method
  result
end

Two or More Empty Lines

Don’t use several empty lines in a row.

# bad - It has two empty lines.
some_method


some_method

# good
some_method

some_method

Empty Lines after Module Inclusion

Use empty lines after module inclusion methods (extend, include and prepend).

# bad
class Foo
  extend SomeModule
  include AnotherModule
  prepend YetAnotherModule
  def foo; end
end

# good
class Foo
  extend SomeModule
  include AnotherModule
  prepend YetAnotherModule

  def foo; end
end

Empty Lines around Attribute Accessor

Use empty lines around attribute accessor.

# bad
class Foo
  attr_reader :foo
  def foo
    # do something...
  end
end

# good
class Foo
  attr_reader :foo

  def foo
    # do something...
  end
end

Empty Lines around Access Modifier

Use empty lines around access modifier.

# bad
class Foo
  def bar; end
  private
  def baz; end
end

# good
class Foo
  def bar; end

  private

  def baz; end
end

Empty Lines around Bodies

Don’t use empty lines around method, class, module, block bodies.

# bad
class Foo

  def foo

    begin

      do_something do

        something

      end

    rescue

      something

    end

    true

  end

end

# good
class Foo
  def foo
    begin
      do_something do
        something
      end
    rescue
      something
    end
  end
end

Trailing Comma in Method Arguments

Avoid comma after the last parameter in a method call, especially when the parameters are not on separate lines.

# bad - easier to move/add/remove parameters, but still not preferred
some_method(
  size,
  count,
  color,
)

# bad
some_method(size, count, color, )

# good
some_method(size, count, color)

Spaces around Equals

Use spaces around the = operator when assigning default values to method parameters:

# bad
def some_method(arg1=:default, arg2=nil, arg3=[])
  # do something...
end

# good
def some_method(arg1 = :default, arg2 = nil, arg3 = [])
  # do something...
end

While several Ruby books suggest the first style, the second is much more prominent in practice (and arguably a bit more readable).

Line Continuation in Expressions

Avoid line continuation with \ where not required. In practice, avoid using line continuations for anything but string concatenation.

# bad (\ is not needed here)
result = 1 - \
         2

# bad (\ is required, but still ugly as hell)
result = 1 \
         - 2

# good
result = 1 -
         2

long_string = 'First part of the long string' \
              ' and second part of the long string'

Multi-line Method Chains

Adopt a consistent multi-line method chaining style. There are two popular styles in the Ruby community, both of which are considered good - leading . and trailing ..

Leading .

When continuing a chained method call on another line, keep the . on the second line.

# bad - need to consult first line to understand second line
one.two.three.
  four

# good - it's immediately clear what's going on the second line
one.two.three
  .four

Trailing .

When continuing a chained method call on another line, include the . on the first line to indicate that the expression continues.

# bad - need to read ahead to the second line to know that the chain continues
one.two.three
  .four

# good - it's immediately clear that the expression continues beyond the first line
one.two.three.
  four

A discussion on the merits of both alternative styles can be found here.

Method Arguments Alignment

Align the arguments of a method call if they span more than one line. When aligning arguments is not appropriate due to line-length constraints, single indent for the lines after the first is also acceptable.

# starting point (line is too long)
def send_mail(source)
  Mailer.deliver(to: 'bob@example.com', from: 'us@example.com', subject: 'Important message', body: source.text)
end

# bad (double indent)
def send_mail(source)
  Mailer.deliver(
      to: 'bob@example.com',
      from: 'us@example.com',
      subject: 'Important message',
      body: source.text)
end

# good
def send_mail(source)
  Mailer.deliver(to: 'bob@example.com',
                 from: 'us@example.com',
                 subject: 'Important message',
                 body: source.text)
end

# good (normal indent)
def send_mail(source)
  Mailer.deliver(
    to: 'bob@example.com',
    from: 'us@example.com',
    subject: 'Important message',
    body: source.text
  )
end

Implicit Options Hash

Important
As of Ruby 2.7 braces around an options hash are no longer optional.

Omit the outer braces around an implicit options hash.

# bad
user.set({ name: 'John', age: 45, permissions: { read: true } })

# good
user.set(name: 'John', age: 45, permissions: { read: true })

DSL Method Calls

Omit both the outer braces and parentheses for methods that are part of an internal DSL (e.g., Rake, Rails, RSpec).

class Person < ActiveRecord::Base
  # bad
  attr_reader(:name, :age)
  # good
  attr_reader :name, :age

  # bad
  validates(:name, { presence: true, length: { within: 1..10 } })
  # good
  validates :name, presence: true, length: { within: 1..10 }
end

Space in Method Calls

Do not put a space between a method name and the opening parenthesis.

# bad
puts (x + y)

# good
puts(x + y)

Space in Brackets Access

Do not put a space between a receiver name and the opening brackets.

# bad
collection [index_or_key]

# good
collection[index_or_key]

Multi-line Arrays Alignment

Align the elements of array literals spanning multiple lines.

# bad - single indent
menu_item = %w[Spam Spam Spam Spam Spam Spam Spam Spam
  Baked beans Spam Spam Spam Spam Spam]

# good
menu_item = %w[
  Spam Spam Spam Spam Spam Spam Spam Spam
  Baked beans Spam Spam Spam Spam Spam
]

# good
menu_item =
  %w[Spam Spam Spam Spam Spam Spam Spam Spam
     Baked beans Spam Spam Spam Spam Spam]

Naming Conventions

The only real difficulties in programming are cache invalidation and naming things.

— Phil Karlton

English for Identifiers

Name identifiers in English.

# bad - identifier is a Bulgarian word, using non-ascii (Cyrillic) characters
заплата = 1_000

# bad - identifier is a Bulgarian word, written with Latin letters (instead of Cyrillic)
zaplata = 1_000

# good
salary = 1_000

Snake Case for Symbols, Methods and Variables

Use snake_case for symbols, methods and variables.

# bad
:'some symbol'
:SomeSymbol
:someSymbol

someVar = 5

def someMethod
  # some code
end

def SomeMethod
  # some code
end

# good
:some_symbol

some_var = 5

def some_method
  # some code
end

Identifiers with a Numeric Suffix

Do not separate numbers from letters on symbols, methods and variables.

# bad
:some_sym_1

some_var_1 = 1

var_10 = 10

def some_method_1
  # some code
end

# good
:some_sym1

some_var1 = 1

var10 = 10

def some_method1
  # some code
end

CapitalCase for Classes and Modules

Note
CapitalCase is also known as UpperCamelCase, CapitalWords and PascalCase.

Use CapitalCase for classes and modules. (Keep acronyms like HTTP, RFC, XML uppercase).

# bad
class Someclass
  # some code
end

class Some_Class
  # some code
end

class SomeXml
  # some code
end

class XmlSomething
  # some code
end

# good
class SomeClass
  # some code
end

class SomeXML
  # some code
end

class XMLSomething
  # some code
end

Snake Case for Files

Use snake_case for naming files, e.g. hello_world.rb.

Snake Case for Directories

Use snake_case for naming directories, e.g. lib/hello_world/hello_world.rb.

One Class per File

Aim to have just a single class/module per source file. Name the file name as the class/module, but replacing CapitalCase with snake_case.

Screaming Snake Case for Constants

Use SCREAMING_SNAKE_CASE for other constants (th