Layout

Layout/AccessModifierIndentation

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Bare access modifiers (those not applying to specific methods) should be indented as deep as method definitions, or as deep as the class/module keyword, depending on configuration.

Examples

EnforcedStyle: indent (default)

# bad
class Plumbus
private
  def smooth; end
end

# good
class Plumbus
  private
  def smooth; end
end

EnforcedStyle: outdent

# bad
class Plumbus
  private
  def smooth; end
end

# good
class Plumbus
private
  def smooth; end
end

Configurable attributes

Name Default value Configurable values

EnforcedStyle

indent

outdent, indent

IndentationWidth

<none>

Integer

Layout/ArgumentAlignment

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.68

0.77

Here we check if the arguments on a multi-line method definition are aligned.

Examples

EnforcedStyle: with_first_argument (default)

# good

foo :bar,
    :baz,
    key: value

foo(
  :bar,
  :baz,
  key: value
)

# bad

foo :bar,
  :baz,
  key: value

foo(
  :bar,
    :baz,
    key: value
)

EnforcedStyle: with_fixed_indentation

# good

foo :bar,
  :baz,
  key: value

# bad

foo :bar,
    :baz,
    key: value

Configurable attributes

Name Default value Configurable values

EnforcedStyle

with_first_argument

with_first_argument, with_fixed_indentation

IndentationWidth

<none>

Integer

Layout/ArrayAlignment

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

0.77

Here we check if the elements of a multi-line array literal are aligned.

Examples

EnforcedStyle: with_first_element (default)

# good

array = [1, 2, 3,
         4, 5, 6]
array = ['run',
         'forrest',
         'run']

# bad

array = [1, 2, 3,
  4, 5, 6]
array = ['run',
     'forrest',
     'run']

EnforcedStyle: with_fixed_indentation

# good

array = [1, 2, 3,
  4, 5, 6]

# bad

array = [1, 2, 3,
         4, 5, 6]

Configurable attributes

Name Default value Configurable values

EnforcedStyle

with_first_element

with_first_element, with_fixed_indentation

IndentationWidth

<none>

Integer

Layout/AssignmentIndentation

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

1.45

Checks the indentation of the first line of the right-hand-side of a multi-line assignment.

The indentation of the remaining lines can be corrected with other cops such as Layout/IndentationConsistency and Layout/EndAlignment.

Examples

# bad
value =
if foo
  'bar'
end

# good
value =
  if foo
    'bar'
  end

Configurable attributes

Name Default value Configurable values

IndentationWidth

<none>

Integer

Layout/BeginEndAlignment

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.91

-

Checks whether the end keyword of begin is aligned properly.

Two modes are supported through the EnforcedStyleAlignWith configuration parameter. If it’s set to start_of_line (which is the default), the end shall be aligned with the start of the line where the begin keyword is. If it’s set to begin, the end shall be aligned with the begin keyword.

Layout/EndAlignment cop aligns with keywords (e.g. if, while, case) by default. On the other hand, ||= begin that this cop targets tends to align with the start of the line, it defaults to EnforcedStyleAlignWith: start_of_line. These style can be configured by each cop.

Examples

EnforcedStyleAlignWith: start_of_line (default)

# bad
foo ||= begin
          do_something
        end

# good
foo ||= begin
  do_something
end

EnforcedStyleAlignWith: begin

# bad
foo ||= begin
  do_something
end

# good
foo ||= begin
          do_something
        end

Configurable attributes

Name Default value Configurable values

EnforcedStyleAlignWith

start_of_line

start_of_line, begin

Severity

warning

String

Layout/BlockAlignment

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.53

-

Checks whether the end keywords are aligned properly for do end blocks.

Three modes are supported through the EnforcedStyleAlignWith configuration parameter:

start_of_block : the end shall be aligned with the start of the line where the do appeared.

start_of_line : the end shall be aligned with the start of the line where the expression started.

either (which is the default) : the end is allowed to be in either location. The autocorrect will default to start_of_line.

Examples

EnforcedStyleAlignWith: either (default)

# bad

foo.bar
  .each do
    baz
      end

# good

foo.bar
  .each do
    baz
end

EnforcedStyleAlignWith: start_of_block

# bad

foo.bar
  .each do
    baz
      end

# good

foo.bar
  .each do
    baz
  end

EnforcedStyleAlignWith: start_of_line

# bad

foo.bar
  .each do
    baz
      end

# good

foo.bar
  .each do
    baz
end

Configurable attributes

Name Default value Configurable values

EnforcedStyleAlignWith

either

either, start_of_block, start_of_line

Layout/BlockEndNewline

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks whether the end statement of a do..end block is on its own line.

Examples

# bad
blah do |i|
  foo(i) end

# good
blah do |i|
  foo(i)
end

# bad
blah { |i|
  foo(i) }

# good
blah { |i|
  foo(i)
}

Layout/CaseIndentation

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

1.16

Checks how the when and ins of a case expression are indented in relation to its case or end keyword.

It will register a separate offense for each misaligned when and in.

Examples

# If Layout/EndAlignment is set to keyword style (default)
# *case* and *end* should always be aligned to same depth,
# and therefore *when* should always be aligned to both -
# regardless of configuration.

# bad for all styles
case n
  when 0
    x * 2
  else
    y / 3
end

case n
  in pattern
    x * 2
  else
    y / 3
end

# good for all styles
case n
when 0
  x * 2
else
  y / 3
end

case n
in pattern
  x * 2
else
  y / 3
end

EnforcedStyle: case (default)

# if EndAlignment is set to other style such as
# start_of_line (as shown below), then *when* alignment
# configuration does have an effect.

# bad
a = case n
when 0
  x * 2
else
  y / 3
end

a = case n
in pattern
  x * 2
else
  y / 3
end

# good
a = case n
    when 0
      x * 2
    else
      y / 3
end

a = case n
    in pattern
      x * 2
    else
      y / 3
end

EnforcedStyle: end

# bad
a = case n
    when 0
      x * 2
    else
      y / 3
end

a = case n
    in pattern
      x * 2
    else
      y / 3
end

# good
a = case n
when 0
  x * 2
else
  y / 3
end

a = case n
in pattern
  x * 2
else
  y / 3
end

Configurable attributes

Name Default value Configurable values

EnforcedStyle

case

case, end

IndentOneStep

false

Boolean

IndentationWidth

<none>

Integer

Layout/ClassStructure

Enabled by default Safe Supports autocorrection Version Added Version Changed

Disabled

Yes

Always (Unsafe)

0.52

1.53

Checks if the code style follows the ExpectedOrder configuration:

Categories allows us to map macro names into a category.

Consider an example of code style that covers the following order:

  • Module inclusion (include, prepend, extend)

  • Constants

  • Associations (has_one, has_many)

  • Public attribute macros (attr_accessor, attr_writer, attr_reader)

  • Other macros (validates, validate)

  • Public class methods

  • Initializer

  • Public instance methods

  • Protected attribute macros (attr_accessor, attr_writer, attr_reader)

  • Protected instance methods

  • Private attribute macros (attr_accessor, attr_writer, attr_reader)

  • Private instance methods

You can configure the following order:

 Layout/ClassStructure:
   ExpectedOrder:
     - module_inclusion
     - constants
     - association
     - public_attribute_macros
     - public_delegate
     - macros
     - public_class_methods
     - initializer
     - public_methods
     - protected_attribute_macros
     - protected_methods
     - private_attribute_macros
     - private_delegate
     - private_methods

Instead of putting all literals in the expected order, is also possible to group categories of macros. Visibility levels are handled automatically.

 Layout/ClassStructure:
   Categories:
     association:
       - has_many
       - has_one
     attribute_macros:
       - attr_accessor
       - attr_reader
       - attr_writer
     macros:
       - validates
       - validate
     module_inclusion:
       - include
       - prepend
       - extend

Safety

Autocorrection is unsafe because class methods and module inclusion can behave differently, based on which methods or constants have already been defined.

Constants will only be moved when they are assigned with literals.

Examples

# bad
# Expect extend be before constant
class Person < ApplicationRecord
  has_many :orders
  ANSWER = 42

  extend SomeModule
  include AnotherModule
end

# good
class Person
  # extend and include go first
  extend SomeModule
  include AnotherModule

  # inner classes
  CustomError = Class.new(StandardError)

  # constants are next
  SOME_CONSTANT = 20

  # afterwards we have public attribute macros
  attr_reader :name

  # followed by other macros (if any)
  validates :name

  # then we have public delegate macros
  delegate :to_s, to: :name

  # public class methods are next in line
  def self.some_method
  end

  # initialization goes between class methods and instance methods
  def initialize
  end

  # followed by other public instance methods
  def some_method
  end

  # protected attribute macros and methods go next
  protected

  attr_reader :protected_name

  def some_protected_method
  end

  # private attribute macros, delegate macros and methods
  # are grouped near the end
  private

  attr_reader :private_name

  delegate :some_private_delegate, to: :name

  def some_private_method
  end
end

Configurable attributes

Name Default value Configurable values

Categories

{"module_inclusion"⇒["include", "prepend", "extend"]}

ExpectedOrder

module_inclusion, constants, public_class_methods, initializer, public_methods, protected_methods, private_methods

Array

Layout/ClosingHeredocIndentation

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.57

-

Checks the indentation of here document closings.

Examples

# bad
class Foo
  def bar
    <<~SQL
      'Hi'
  SQL
  end
end

# good
class Foo
  def bar
    <<~SQL
      'Hi'
    SQL
  end
end

# bad

# heredoc contents is before closing heredoc.
foo arg,
    <<~EOS
  Hi
    EOS

# good
foo arg,
    <<~EOS
  Hi
EOS

# good
foo arg,
    <<~EOS
      Hi
    EOS

Layout/ClosingParenthesisIndentation

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks the indentation of hanging closing parentheses in method calls, method definitions, and grouped expressions. A hanging closing parenthesis means ) preceded by a line break.

Examples

# bad
some_method(
  a,
  b
  )

some_method(
  a, b
  )

some_method(a, b, c
  )

some_method(a,
            b,
            c
  )

some_method(a,
  x: 1,
  y: 2
  )

# Scenario 1: When First Parameter Is On Its Own Line

# good: when first param is on a new line, right paren is *always*
#       outdented by IndentationWidth
some_method(
  a,
  b
)

# good
some_method(
  a, b
)

# Scenario 2: When First Parameter Is On The Same Line

# good: when all other params are also on the same line, outdent
#       right paren by IndentationWidth
some_method(a, b, c
           )

# good: when all other params are on multiple lines, but are lined
#       up, align right paren with left paren
some_method(a,
            b,
            c
           )

# good: when other params are not lined up on multiple lines, outdent
#       right paren by IndentationWidth
some_method(a,
  x: 1,
  y: 2
)

Layout/CommentIndentation

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

1.24

Checks the indentation of comments.

Examples

# bad
  # comment here
def method_name
end

  # comment here
a = 'hello'

# yet another comment
  if true
    true
  end

# good
# comment here
def method_name
end

# comment here
a = 'hello'

# yet another comment
if true
  true
end

AllowForAlignment: false (default)

# bad
a = 1 # A really long comment
      # spanning two lines.

# good
# A really long comment spanning one line.
a = 1

AllowForAlignment: true

# good
a = 1 # A really long comment
      # spanning two lines.

Configurable attributes

Name Default value Configurable values

AllowForAlignment

false

Boolean

Layout/ConditionPosition

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.53

0.83

Checks for conditions that are not on the same line as if/while/until.

Examples

# bad
if
  some_condition
  do_something
end

# good
if some_condition
  do_something
end

Layout/DefEndAlignment

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.53

-

Checks whether the end keywords of method definitions are aligned properly.

Two modes are supported through the EnforcedStyleAlignWith configuration parameter. If it’s set to start_of_line (which is the default), the end shall be aligned with the start of the line where the def keyword is. If it’s set to def, the end shall be aligned with the def keyword.

Examples

EnforcedStyleAlignWith: start_of_line (default)

# bad

private def foo
            end

# good

private def foo
end

EnforcedStyleAlignWith: def

# bad

private def foo
            end

# good

private def foo
        end

Configurable attributes

Name Default value Configurable values

EnforcedStyleAlignWith

start_of_line

start_of_line, def

Severity

warning

String

Layout/DotPosition

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks the . position in multi-line method calls.

Examples

EnforcedStyle: leading (default)

# bad
something.
  method

# good
something
  .method

EnforcedStyle: trailing

# bad
something
  .method

# good
something.
  method

Configurable attributes

Name Default value Configurable values

EnforcedStyle

leading

leading, trailing

Layout/ElseAlignment

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks the alignment of else keywords. Normally they should be aligned with an if/unless/while/until/begin/def/rescue keyword, but there are special cases when they should follow the same rules as the alignment of end.

Examples

# bad
if something
  code
 else
  code
end

# bad
if something
  code
 elsif something
  code
end

# good
if something
  code
else
  code
end

Layout/EmptyComment

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Command-line only

0.53

1.61

Checks empty comment.

Examples

# bad

#
class Foo
end

# good

#
# Description of `Foo` class.
#
class Foo
end

AllowBorderComment: true (default)

# good

def foo
end

#################

def bar
end

AllowBorderComment: false

# bad

def foo
end

#################

def bar
end

AllowMarginComment: true (default)

# good

#
# Description of `Foo` class.
#
class Foo
end

AllowMarginComment: false

# bad

#
# Description of `Foo` class.
#
class Foo
end

Configurable attributes

Name Default value Configurable values

AllowBorderComment

true

Boolean

AllowMarginComment

true

Boolean

Layout/EmptyLineAfterGuardClause

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.56

0.59

Enforces empty line after guard clause.

This cop allows # :nocov: directive after guard clause because SimpleCov excludes code from the coverage report by wrapping it in # :nocov::

def foo
  # :nocov:
  return if condition
  # :nocov:
  bar
end

Refer to SimpleCov’s documentation for more details: https://github.com/simplecov-ruby/simplecov#ignoringskipping-code

Examples

# bad
def foo
  return if need_return?
  bar
end

# good
def foo
  return if need_return?

  bar
end

# good
def foo
  return if something?
  return if something_different?

  bar
end

# also good
def foo
  if something?
    do_something
    return if need_return?
  end
end

Layout/EmptyLineAfterMagicComment

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks for a newline after the final magic comment.

Examples

# good
# frozen_string_literal: true

# Some documentation for Person
class Person
  # Some code
end

# bad
# frozen_string_literal: true
# Some documentation for Person
class Person
  # Some code
end

Layout/EmptyLineAfterMultilineCondition

Enabled by default Safe Supports autocorrection Version Added Version Changed

Disabled

Yes

Always

0.90

-

Enforces empty line after multiline condition.

Examples

# bad
if multiline &&
  condition
  do_something
end

# good
if multiline &&
  condition

  do_something
end

# bad
case x
when foo,
  bar
  do_something
end

# good
case x
when foo,
  bar

  do_something
end

# bad
begin
  do_something
rescue FooError,
  BarError
  handle_error
end

# good
begin
  do_something
rescue FooError,
  BarError

  handle_error
end

Layout/EmptyLineBetweenDefs

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

1.23

Checks whether class/module/method definitions are separated by one or more empty lines.

NumberOfEmptyLines can be an integer (default is 1) or an array (e.g. [1, 2]) to specify a minimum and maximum number of empty lines permitted.

AllowAdjacentOneLineDefs configures whether adjacent one-line definitions are considered an offense.

Examples

EmptyLineBetweenMethodDefs: true (default)

# checks for empty lines between method definitions.

# bad
def a
end
def b
end
# good
def a
end

def b
end

EmptyLineBetweenClassDefs: true (default)

# checks for empty lines between class definitions.

# bad
class A
end
class B
end
def b
end
# good
class A
end

class B
end

def b
end

EmptyLineBetweenModuleDefs: true (default)

# checks for empty lines between module definitions.

# bad
module A
end
module B
end
def b
end
# good
module A
end

module B
end

def b
end

AllowAdjacentOneLineDefs: true (default)

# good
class ErrorA < BaseError; end
class ErrorB < BaseError; end
class ErrorC < BaseError; end

# good
class ErrorA < BaseError; end

class ErrorB < BaseError; end

class ErrorC < BaseError; end

AllowAdjacentOneLineDefs: false

# bad
class ErrorA < BaseError; end
class ErrorB < BaseError; end
class ErrorC < BaseError; end

# good
class ErrorA < BaseError; end

class ErrorB < BaseError; end

class ErrorC < BaseError; end

Configurable attributes

Name Default value Configurable values

EmptyLineBetweenMethodDefs

true

Boolean

EmptyLineBetweenClassDefs

true

Boolean

EmptyLineBetweenModuleDefs

true

Boolean

DefLikeMacros

[]

Array

AllowAdjacentOneLineDefs

true

Boolean

NumberOfEmptyLines

1

Integer

Layout/EmptyLines

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks for two or more consecutive blank lines.

Examples

# bad - It has two empty lines.
some_method
# one empty line
# two empty lines
some_method

# good
some_method
# one empty line
some_method

Layout/EmptyLinesAroundAccessModifier

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Access modifiers should be surrounded by blank lines.

Examples

EnforcedStyle: around (default)

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

# good
class Foo
  def bar; end

  private

  def baz; end
end

EnforcedStyle: only_before

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

# good
class Foo
  def bar; end

  private
  def baz; end
end

Configurable attributes

Name Default value Configurable values

EnforcedStyle

around

around, only_before

Layout/EmptyLinesAroundArguments

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.52

-

Checks if empty lines exist around the arguments of a method invocation.

Examples

# bad
do_something(
  foo

)

process(bar,

        baz: qux,
        thud: fred)

some_method(

  [1,2,3],
  x: y
)

# good
do_something(
  foo
)

process(bar,
        baz: qux,
        thud: fred)

some_method(
  [1,2,3],
  x: y
)

Layout/EmptyLinesAroundAttributeAccessor

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.83

0.84

Checks for a newline after an attribute accessor or a group of them. alias syntax and alias_method, public, protected, and private methods are allowed by default. These are customizable with AllowAliasSyntax and AllowedMethods options.

Examples

# bad
attr_accessor :foo
def do_something
end

# good
attr_accessor :foo

def do_something
end

# good
attr_accessor :foo
attr_reader :bar
attr_writer :baz
attr :qux

def do_something
end

AllowAliasSyntax: true (default)

# good
attr_accessor :foo
alias :foo? :foo

def do_something
end

AllowAliasSyntax: false

# bad
attr_accessor :foo
alias :foo? :foo

def do_something
end

# good
attr_accessor :foo

alias :foo? :foo

def do_something
end

AllowedMethods: ['private']

# good
attr_accessor :foo
private :foo

def do_something
end

Configurable attributes

Name Default value Configurable values

AllowAliasSyntax

true

Boolean

AllowedMethods

alias_method, public, protected, private

Array

Layout/EmptyLinesAroundBeginBody

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks if empty lines exist around the bodies of begin-end blocks.

Examples

# good

begin
  # ...
end

# bad

begin

  # ...

end

Layout/EmptyLinesAroundBlockBody

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks if empty lines around the bodies of blocks match the configuration.

Examples

EnforcedStyle: no_empty_lines (default)

# good

foo do |bar|
  # ...
end

EnforcedStyle: empty_lines

# good

foo do |bar|

  # ...

end

Configurable attributes

Name Default value Configurable values

EnforcedStyle

no_empty_lines

empty_lines, no_empty_lines

Layout/EmptyLinesAroundClassBody

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

0.53

Checks if empty lines around the bodies of classes match the configuration.

Examples

EnforcedStyle: no_empty_lines (default)

# good

class Foo
  def bar
    # ...
  end
end

EnforcedStyle: empty_lines

# good

class Foo

  def bar
    # ...
  end

end

EnforcedStyle: empty_lines_except_namespace

# good

class Foo
  class Bar

    # ...

  end
end

EnforcedStyle: empty_lines_special

# good
class Foo

  def bar; end

end

EnforcedStyle: beginning_only

# good

class Foo

  def bar
    # ...
  end
end

EnforcedStyle: ending_only

# good

class Foo
  def bar
    # ...
  end

end

Configurable attributes

Name Default value Configurable values

EnforcedStyle

no_empty_lines

empty_lines, empty_lines_except_namespace, empty_lines_special, no_empty_lines, beginning_only, ending_only

Layout/EmptyLinesAroundExceptionHandlingKeywords

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks if empty lines exist around the bodies of begin sections. This cop doesn’t check empty lines at begin body beginning/end and around method definition body. Style/EmptyLinesAroundBeginBody or Style/EmptyLinesAroundMethodBody can be used for this purpose.

Examples

# good

begin
  do_something
rescue
  do_something2
else
  do_something3
ensure
  do_something4
end

# good

def foo
  do_something
rescue
  do_something2
end

# bad

begin
  do_something

rescue

  do_something2

else

  do_something3

ensure

  do_something4
end

# bad

def foo
  do_something

rescue

  do_something2
end

Layout/EmptyLinesAroundMethodBody

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks if empty lines exist around the bodies of methods.

Examples

# good

def foo
  # ...
end

# bad

def bar

  # ...

end

Layout/EmptyLinesAroundModuleBody

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks if empty lines around the bodies of modules match the configuration.

Examples

EnforcedStyle: no_empty_lines (default)

# good

module Foo
  def bar
    # ...
  end
end

EnforcedStyle: empty_lines

# good

module Foo

  def bar
    # ...
  end

end

EnforcedStyle: empty_lines_except_namespace

# good

module Foo
  module Bar

    # ...

  end
end

EnforcedStyle: empty_lines_special

# good
module Foo

  def bar; end

end

Configurable attributes

Name Default value Configurable values

EnforcedStyle

no_empty_lines

empty_lines, empty_lines_except_namespace, empty_lines_special, no_empty_lines

Layout/EndAlignment

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.53

-

Checks whether the end keywords are aligned properly.

Three modes are supported through the EnforcedStyleAlignWith configuration parameter:

If it’s set to keyword (which is the default), the end shall be aligned with the start of the keyword (if, class, etc.).

If it’s set to variable the end shall be aligned with the left-hand-side of the variable assignment, if there is one.

If it’s set to start_of_line, the end shall be aligned with the start of the line where the matching keyword appears.

This Layout/EndAlignment cop aligns with keywords (e.g. if, while, case) by default. On the other hand, Layout/BeginEndAlignment cop aligns with EnforcedStyleAlignWith: start_of_line by default due to ||= begin tends to align with the start of the line. Layout/DefEndAlignment cop also aligns with EnforcedStyleAlignWith: start_of_line by default. These style can be configured by each cop.

Examples

EnforcedStyleAlignWith: keyword (default)

# bad

variable = if true
    end

# good

variable = if true
           end

variable =
  if true
  end

EnforcedStyleAlignWith: variable

# bad

variable = if true
    end

# good

variable = if true
end

variable =
  if true
  end

EnforcedStyleAlignWith: start_of_line

# bad

variable = if true
    end

puts(if true
     end)

# good

variable = if true
end

puts(if true
end)

variable =
  if true
  end

Configurable attributes

Name Default value Configurable values

EnforcedStyleAlignWith

keyword

keyword, variable, start_of_line

Severity

warning

String

Layout/EndOfLine

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

No

0.49

-

Checks for Windows-style line endings in the source code.

Examples

EnforcedStyle: native (default)

# The `native` style means that CR+LF (Carriage Return + Line Feed) is
# enforced on Windows, and LF is enforced on other platforms.

# bad
puts 'Hello' # Return character is LF on Windows.
puts 'Hello' # Return character is CR+LF on other than Windows.

# good
puts 'Hello' # Return character is CR+LF on Windows.
puts 'Hello' # Return character is LF on other than Windows.

EnforcedStyle: lf

# The `lf` style means that LF (Line Feed) is enforced on
# all platforms.

# bad
puts 'Hello' # Return character is CR+LF on all platforms.

# good
puts 'Hello' # Return character is LF on all platforms.

EnforcedStyle: crlf

# The `crlf` style means that CR+LF (Carriage Return + Line Feed) is
# enforced on all platforms.

# bad
puts 'Hello' # Return character is LF on all platforms.

# good
puts 'Hello' # Return character is CR+LF on all platforms.

Configurable attributes

Name Default value Configurable values

EnforcedStyle

native

native, lf, crlf

Layout/ExtraSpacing

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks for extra/unnecessary whitespace.

Examples

# good if AllowForAlignment is true
name      = "RuboCop"
# Some comment and an empty line

website  += "/rubocop/rubocop" unless cond
puts        "rubocop"          if     debug

# bad for any configuration
set_app("RuboCop")
website  = "https://github.com/rubocop/rubocop"

# good only if AllowBeforeTrailingComments is true
object.method(arg)  # this is a comment

# good even if AllowBeforeTrailingComments is false or not set
object.method(arg) # this is a comment

# good with either AllowBeforeTrailingComments or AllowForAlignment
object.method(arg)         # this is a comment
another_object.method(arg) # this is another comment
some_object.method(arg)    # this is some comment

Configurable attributes

Name Default value Configurable values

AllowForAlignment

true

Boolean

AllowBeforeTrailingComments

false

Boolean

ForceEqualSignAlignment

false

Boolean

Layout/FirstArgumentIndentation

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.68

0.77

Checks the indentation of the first argument in a method call. Arguments after the first one are checked by Layout/ArgumentAlignment, not by this cop.

For indenting the first parameter of method definitions, check out Layout/FirstParameterIndentation.

This cop will respect Layout/ArgumentAlignment and will not work when EnforcedStyle: with_fixed_indentation is specified for Layout/ArgumentAlignment.

Examples

# bad
some_method(
first_param,
second_param)

foo = some_method(
first_param,
second_param)

foo = some_method(nested_call(
nested_first_param),
second_param)

foo = some_method(
nested_call(
nested_first_param),
second_param)

some_method nested_call(
nested_first_param),
second_param

EnforcedStyle: special_for_inner_method_call_in_parentheses (default)

# Same as `special_for_inner_method_call` except that the special rule
# only applies if the outer method call encloses its arguments in
# parentheses.

# good
some_method(
  first_param,
second_param)

foo = some_method(
  first_param,
second_param)

foo = some_method(nested_call(
                    nested_first_param),
second_param)

foo = some_method(
  nested_call(
    nested_first_param),
second_param)

some_method nested_call(
  nested_first_param),
second_param

EnforcedStyle: consistent

# The first argument should always be indented one step more than the
# preceding line.

# good
some_method(
  first_param,
second_param)

foo = some_method(
  first_param,
second_param)

foo = some_method(nested_call(
  nested_first_param),
second_param)

foo = some_method(
  nested_call(
    nested_first_param),
second_param)

some_method nested_call(
  nested_first_param),
second_param

EnforcedStyle: consistent_relative_to_receiver

# The first argument should always be indented one level relative to
# the parent that is receiving the argument

# good
some_method(
  first_param,
second_param)

foo = some_method(
        first_param,
second_param)

foo = some_method(nested_call(
                    nested_first_param),
second_param)

foo = some_method(
        nested_call(
          nested_first_param),
second_param)

some_method nested_call(
              nested_first_param),
second_params

EnforcedStyle: special_for_inner_method_call

# The first argument should normally be indented one step more than
# the preceding line, but if it's an argument for a method call that
# is itself an argument in a method call, then the inner argument
# should be indented relative to the inner method.

# good
some_method(
  first_param,
second_param)

foo = some_method(
  first_param,
second_param)

foo = some_method(nested_call(
                    nested_first_param),
second_param)

foo = some_method(
  nested_call(
    nested_first_param),
second_param)

some_method nested_call(
              nested_first_param),
second_param

Configurable attributes

Name Default value Configurable values

EnforcedStyle

special_for_inner_method_call_in_parentheses

consistent, consistent_relative_to_receiver, special_for_inner_method_call, special_for_inner_method_call_in_parentheses

IndentationWidth

<none>

Integer

Layout/FirstArrayElementIndentation

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.68

0.77

Checks the indentation of the first element in an array literal where the opening bracket and the first element are on separate lines. The other elements' indentations are handled by Layout/ArrayAlignment cop.

This cop will respect Layout/ArrayAlignment and will not work when EnforcedStyle: with_fixed_indentation is specified for Layout/ArrayAlignment.

By default, array literals that are arguments in a method call with parentheses, and where the opening square bracket of the array is on the same line as the opening parenthesis of the method call, shall have their first element indented one step (two spaces) more than the position inside the opening parenthesis.

Other array literals shall have their first element indented one step more than the start of the line where the opening square bracket is.

This default style is called 'special_inside_parentheses'. Alternative styles are 'consistent' and 'align_brackets'. Here are examples:

Examples

EnforcedStyle: special_inside_parentheses (default)

# The `special_inside_parentheses` style enforces that the first
# element in an array literal where the opening bracket and first
# element are on separate lines is indented one step (two spaces) more
# than the position inside the opening parenthesis.

# bad
array = [
  :value
]
and_in_a_method_call([
  :no_difference
                     ])

# good
array = [
  :value
]
but_in_a_method_call([
                       :its_like_this
                     ])

EnforcedStyle: consistent

# The `consistent` style enforces that the first element in an array
# literal where the opening bracket and the first element are on
# separate lines is indented the same as an array literal which is not
# defined inside a method call.

# bad
array = [
  :value
]
but_in_a_method_call([
                       :its_like_this
])

# good
array = [
  :value
]
and_in_a_method_call([
  :no_difference
])

EnforcedStyle: align_brackets

# The `align_brackets` style enforces that the opening and closing
# brackets are indented to the same position.

# bad
and_now_for_something = [
                          :completely_different
]

# good
and_now_for_something = [
                          :completely_different
                        ]

Configurable attributes

Name Default value Configurable values

EnforcedStyle

special_inside_parentheses

special_inside_parentheses, consistent, align_brackets

IndentationWidth

<none>

Integer

Layout/FirstArrayElementLineBreak

Enabled by default Safe Supports autocorrection Version Added Version Changed

Disabled

Yes

Always

0.49

-

Checks for a line break before the first element in a multi-line array.

Examples

# bad
[ :a,
  :b]

# good
[
  :a,
  :b]

# good
[:a, :b]

AllowMultilineFinalElement: false (default)

# bad
[ :a, {
  :b => :c
}]

# good
[
  :a, {
  :b => :c
}]

AllowMultilineFinalElement: true

# good
[:a, {
  :b => :c
}]

Configurable attributes

Name Default value Configurable values

AllowMultilineFinalElement

false

Boolean

Layout/FirstHashElementIndentation

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.68

0.77

Checks the indentation of the first key in a hash literal where the opening brace and the first key are on separate lines. The other keys' indentations are handled by the HashAlignment cop.

By default, Hash literals that are arguments in a method call with parentheses, and where the opening curly brace of the hash is on the same line as the opening parenthesis of the method call, shall have their first key indented one step (two spaces) more than the position inside the opening parenthesis.

Other hash literals shall have their first key indented one step more than the start of the line where the opening curly brace is.

This default style is called 'special_inside_parentheses'. Alternative styles are 'consistent' and 'align_braces'. Here are examples:

Examples

EnforcedStyle: special_inside_parentheses (default)

# The `special_inside_parentheses` style enforces that the first key
# in a hash literal where the opening brace and the first key are on
# separate lines is indented one step (two spaces) more than the
# position inside the opening parentheses.

# bad
hash = {
  key: :value
}
and_in_a_method_call({
  no: :difference
                     })
takes_multi_pairs_hash(x: {
  a: 1,
  b: 2
},
                       y: {
                         c: 1,
                         d: 2
                       })

# good
special_inside_parentheses
hash = {
  key: :value
}
but_in_a_method_call({
                       its_like: :this
                     })
takes_multi_pairs_hash(x: {
                         a: 1,
                         b: 2
                       },
                       y: {
                         c: 1,
                         d: 2
                       })

EnforcedStyle: consistent

# The `consistent` style enforces that the first key in a hash
# literal where the opening brace and the first key are on
# separate lines is indented the same as a hash literal which is not
# defined inside a method call.

# bad
hash = {
  key: :value
}
but_in_a_method_call({
                       its_like: :this
                      })

# good
hash = {
  key: :value
}
and_in_a_method_call({
  no: :difference
})

EnforcedStyle: align_braces

# The `align_brackets` style enforces that the opening and closing
# braces are indented to the same position.

# bad
and_now_for_something = {
                          completely: :different
}
takes_multi_pairs_hash(x: {
  a: 1,
  b: 2
},
                        y: {
                             c: 1,
                             d: 2
                           })

# good
and_now_for_something = {
                          completely: :different
                        }
takes_multi_pairs_hash(x: {
                            a: 1,
                            b: 2
                          },
                       y: {
                            c: 1,
                            d: 2
                          })

Configurable attributes

Name Default value Configurable values

EnforcedStyle

special_inside_parentheses

special_inside_parentheses, consistent, align_braces

IndentationWidth

<none>

Integer

Layout/FirstHashElementLineBreak

Enabled by default Safe Supports autocorrection Version Added Version Changed

Disabled

Yes

Always

0.49

-

Checks for a line break before the first element in a multi-line hash.

Examples

# bad
{ a: 1,
  b: 2}

# good
{
  a: 1,
  b: 2 }

# good
{
  a: 1, b: {
  c: 3
}}

AllowMultilineFinalElement: false (default)

# bad
{ a: 1, b: {
  c: 3
}}

AllowMultilineFinalElement: true

# bad
{ a: 1,
  b: {
  c: 3
}}

# good
{ a: 1, b: {
  c: 3
}}

Configurable attributes

Name Default value Configurable values

AllowMultilineFinalElement

false

Boolean

Layout/FirstMethodArgumentLineBreak

Enabled by default Safe Supports autocorrection Version Added Version Changed

Disabled

Yes

Always

0.49

-

Checks for a line break before the first argument in a multi-line method call.

Examples

# bad
method(foo, bar,
  baz)

# good
method(
  foo, bar,
  baz)

  # ignored
  method foo, bar,
    baz

AllowMultilineFinalElement: false (default)

# bad
method(foo, bar, {
  baz: "a",
  qux: "b",
})

# good
method(
  foo, bar, {
  baz: "a",
  qux: "b",
})

AllowMultilineFinalElement: true

# bad
method(foo,
  bar,
  {
    baz: "a",
    qux: "b",
  }
)

# good
method(foo, bar, {
  baz: "a",
  qux: "b",
})

# good
method(
  foo,
  bar,
  {
    baz: "a",
    qux: "b",
  }
)

AllowedMethods: ['some_method']

# good
some_method(foo, bar,
  baz)

Configurable attributes

Name Default value Configurable values

AllowMultilineFinalElement

false

Boolean

AllowedMethods

[]

Array

Layout/FirstMethodParameterLineBreak

Enabled by default Safe Supports autocorrection Version Added Version Changed

Disabled

Yes

Always

0.49

-

Checks for a line break before the first parameter in a multi-line method parameter definition.

Examples

# bad
def method(foo, bar,
    baz)
  do_something
end

# good
def method(
    foo, bar,
    baz)
  do_something
end

# ignored
def method foo,
    bar
  do_something
end

AllowMultilineFinalElement: false (default)

# bad
def method(foo, bar, baz = {
  :a => "b",
})
  do_something
end

# good
def method(
  foo, bar, baz = {
  :a => "b",
})
  do_something
end

AllowMultilineFinalElement: true

# good
def method(foo, bar, baz = {
  :a => "b",
})
  do_something
end

Configurable attributes

Name Default value Configurable values

AllowMultilineFinalElement

false

Boolean

Layout/FirstParameterIndentation

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

0.77

Checks the indentation of the first parameter in a method definition. Parameters after the first one are checked by Layout/ParameterAlignment, not by this cop.

For indenting the first argument of method calls, check out Layout/FirstArgumentIndentation, which supports options related to nesting that are irrelevant for method definitions.

Examples

# bad
def some_method(
first_param,
second_param)
  123
end

EnforcedStyle: consistent (default)

# The first parameter should always be indented one step more than the
# preceding line.

# good
def some_method(
  first_param,
second_param)
  123
end

EnforcedStyle: align_parentheses

# The first parameter should always be indented one step more than the
# opening parenthesis.

# good
def some_method(
                 first_param,
second_param)
  123
end

Configurable attributes

Name Default value Configurable values

EnforcedStyle

consistent

consistent, align_parentheses

IndentationWidth

<none>

Integer

Layout/HashAlignment

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

1.16

Check that the keys, separators, and values of a multi-line hash literal are aligned according to configuration. The configuration options are:

  • key (left align keys, one space before hash rockets and values)

  • separator (align hash rockets and colons, right align keys)

  • table (left align keys, hash rockets, and values)

The treatment of hashes passed as the last argument to a method call can also be configured. The options are:

  • always_inspect

  • always_ignore

  • ignore_implicit (without curly braces)

Alternatively you can specify multiple allowed styles. That’s done by passing a list of styles to EnforcedStyles.

Examples

EnforcedHashRocketStyle: key (default)

# bad
{
  :foo => bar,
   :ba => baz
}
{
  :foo => bar,
  :ba  => baz
}

# good
{
  :foo => bar,
  :ba => baz
}

EnforcedHashRocketStyle: separator

# bad
{
  :foo => bar,
  :ba => baz
}
{
  :foo => bar,
  :ba  => baz
}

# good
{
  :foo => bar,
   :ba => baz
}

EnforcedHashRocketStyle: table

# bad
{
  :foo => bar,
   :ba => baz
}

# good
{
  :foo => bar,
  :ba  => baz
}

EnforcedColonStyle: key (default)

# bad
{
  foo: bar,
   ba: baz
}
{
  foo: bar,
  ba:  baz
}

# good
{
  foo: bar,
  ba: baz
}

EnforcedColonStyle: separator

# bad
{
  foo: bar,
  ba: baz
}

# good
{
  foo: bar,
   ba: baz
}

EnforcedColonStyle: table

# bad
{
  foo: bar,
  ba: baz
}

# good
{
  foo: bar,
  ba:  baz
}

EnforcedLastArgumentHashStyle: always_inspect (default)

# Inspect both implicit and explicit hashes.

# bad
do_something(foo: 1,
  bar: 2)

# bad
do_something({foo: 1,
  bar: 2})

# good
do_something(foo: 1,
             bar: 2)

# good
do_something(
  foo: 1,
  bar: 2
)

# good
do_something({foo: 1,
              bar: 2})

# good
do_something({
  foo: 1,
  bar: 2
})

EnforcedLastArgumentHashStyle: always_ignore

# Ignore both implicit and explicit hashes.

# good
do_something(foo: 1,
  bar: 2)

# good
do_something({foo: 1,
  bar: 2})

EnforcedLastArgumentHashStyle: ignore_implicit

# Ignore only implicit hashes.

# bad
do_something({foo: 1,
  bar: 2})

# good
do_something(foo: 1,
  bar: 2)

EnforcedLastArgumentHashStyle: ignore_explicit

# Ignore only explicit hashes.

# bad
do_something(foo: 1,
  bar: 2)

# good
do_something({foo: 1,
  bar: 2})

Configurable attributes

Name Default value Configurable values

EnforcedHashRocketStyle

key

key, separator, table

EnforcedColonStyle

key

key, separator, table

EnforcedLastArgumentHashStyle

always_inspect

always_inspect, always_ignore, ignore_implicit, ignore_explicit

Layout/HeredocArgumentClosingParenthesis

Enabled by default Safe Supports autocorrection Version Added Version Changed

Disabled

Yes

Always

0.68

-

Checks for the placement of the closing parenthesis in a method call that passes a HEREDOC string as an argument. It should be placed at the end of the line containing the opening HEREDOC tag.

Examples

# bad

   foo(<<-SQL
     bar
   SQL
   )

   foo(<<-SQL, 123, <<-NOSQL,
     bar
   SQL
     baz
   NOSQL
   )

   foo(
     bar(<<-SQL
       baz
     SQL
     ),
     123,
   )

# good

   foo(<<-SQL)
     bar
   SQL

   foo(<<-SQL, 123, <<-NOSQL)
     bar
   SQL
     baz
   NOSQL

   foo(
     bar(<<-SQL),
       baz
     SQL
     123,
   )

Layout/HeredocIndentation

Required Ruby version: 2.3
Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

0.85

Checks the indentation of the here document bodies. The bodies are indented one step.

When Layout/LineLength's AllowHeredoc is false (not default), this cop does not add any offenses for long here documents to avoid Layout/LineLength's offenses.

Examples

# bad
<<-RUBY
something
RUBY

# good
<<~RUBY
  something
RUBY

Layout/IndentationConsistency

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks for inconsistent indentation.

The difference between indented_internal_methods and normal is that the indented_internal_methods style prescribes that in classes and modules the protected and private modifier keywords shall be indented the same as public methods and that protected and private members shall be indented one step more than the modifiers. Other than that, both styles mean that entities on the same logical depth shall have the same indentation.

Examples

EnforcedStyle: normal (default)

# bad
class A
  def test
    puts 'hello'
     puts 'world'
  end
end

# bad
class A
  def test
    puts 'hello'
    puts 'world'
  end

  protected

    def foo
    end

  private

    def bar
    end
end

# good
class A
  def test
    puts 'hello'
    puts 'world'
  end
end

# good
class A
  def test
    puts 'hello'
    puts 'world'
  end

  protected

  def foo
  end

  private

  def bar
  end
end

EnforcedStyle: indented_internal_methods

# bad
class A
  def test
    puts 'hello'
     puts 'world'
  end
end

# bad
class A
  def test
    puts 'hello'
    puts 'world'
  end

  protected

  def foo
  end

  private

  def bar
  end
end

# good
class A
  def test
    puts 'hello'
    puts 'world'
  end
end

# good
class A
  def test
    puts 'hello'
    puts 'world'
  end

  protected

    def foo
    end

  private

    def bar
    end
end

Configurable attributes

Name Default value Configurable values

EnforcedStyle

normal

normal, indented_internal_methods

Layout/IndentationStyle

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

0.82

Checks that the indentation method is consistent. Either tabs only or spaces only are used for indentation.

Examples

EnforcedStyle: spaces (default)

# bad
# This example uses a tab to indent bar.
def foo
  bar
end

# good
# This example uses spaces to indent bar.
def foo
  bar
end

EnforcedStyle: tabs

# bad
# This example uses spaces to indent bar.
def foo
  bar
end

# good
# This example uses a tab to indent bar.
def foo
  bar
end

Configurable attributes

Name Default value Configurable values

IndentationWidth

<none>

Integer

EnforcedStyle

spaces

spaces, tabs

Layout/IndentationWidth

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks for indentation that doesn’t use the specified number of spaces. The indentation width can be configured using the Width setting. The default width is 2.

See also the Layout/IndentationConsistency cop which is the companion to this one.

Examples

Width: 2 (default)

# bad
class A
 def test
  puts 'hello'
 end
end

# good
class A
  def test
    puts 'hello'
  end
end

AllowedPatterns: ['^\s*module']

# bad
module A
class B
  def test
  puts 'hello'
  end
end
end

# good
module A
class B
  def test
    puts 'hello'
  end
end
end

Configurable attributes

Name Default value Configurable values

Width

2

Integer

AllowedPatterns

[]

Array

Layout/InitialIndentation

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks for indentation of the first non-blank non-comment line in a file.

Examples

# bad
   class A
     def foo; end
   end

# good
class A
  def foo; end
end

Layout/LeadingCommentSpace

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

0.73

Checks whether comments have a leading space after the denoting the start of the comment. The leading space is not required for some RDoc special syntax, like ++, --, :nodoc, =begin- and =end comments, "shebang" directives, or rackup options.

Examples

# bad
#Some comment

# good
# Some comment

AllowDoxygenCommentStyle: false (default)

# bad

#**
# Some comment
# Another line of comment
#*

AllowDoxygenCommentStyle: true

# good

#**
# Some comment
# Another line of comment
#*

AllowGemfileRubyComment: false (default)

# bad

#ruby=2.7.0
#ruby-gemset=myproject

AllowGemfileRubyComment: true

# good

#ruby=2.7.0
#ruby-gemset=myproject

AllowRBSInlineAnnotation: false (default)

# bad

include Enumerable #[Integer]

attr_reader :name #: String
attr_reader :age  #: Integer?

AllowRBSInlineAnnotation: true

# good

include Enumerable #[Integer]

attr_reader :name #: String
attr_reader :age  #: Integer?

AllowSteepAnnotation: false (default)

# bad
[1, 2, 3].each_with_object([]) do |n, list| #$ Array[Integer]
  list << n
end

name = 'John'      #: String

AllowSteepAnnotation: true

# good

[1, 2, 3].each_with_object([]) do |n, list| #$ Array[Integer]
  list << n
end

name = 'John'      #: String

Configurable attributes

Name Default value Configurable values

AllowDoxygenCommentStyle

false

Boolean

AllowGemfileRubyComment

false

Boolean

AllowRBSInlineAnnotation

false

Boolean

AllowSteepAnnotation

false

Boolean

Layout/LeadingEmptyLines

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.57

0.77

Checks for unnecessary leading blank lines at the beginning of a file.

Examples

# bad
# (start of file)

class Foo
end

# bad
# (start of file)

# a comment

# good
# (start of file)
class Foo
end

# good
# (start of file)
# a comment

Layout/LineContinuationLeadingSpace

Enabled by default Safe Supports autocorrection Version Added Version Changed

Pending

Yes

Always

1.31

1.45

Checks that strings broken over multiple lines (by a backslash) contain trailing spaces instead of leading spaces (default) or leading spaces instead of trailing spaces.

Examples

EnforcedStyle: trailing (default)

# bad
'this text contains a lot of' \
'               spaces'

# good
'this text contains a lot of               ' \
'spaces'

# bad
'this text is too' \
' long'

# good
'this text is too ' \
'long'

EnforcedStyle: leading

# bad
'this text contains a lot of               ' \
'spaces'

# good
'this text contains a lot of' \
'               spaces'

# bad
'this text is too ' \
'long'

# good
'this text is too' \
' long'

Configurable attributes

Name Default value Configurable values

EnforcedStyle

trailing

leading, trailing

Layout/LineContinuationSpacing

Enabled by default Safe Supports autocorrection Version Added Version Changed

Pending

Yes

Always

1.31

-

Checks that the backslash of a line continuation is separated from preceding text by exactly one space (default) or zero spaces.

Examples

EnforcedStyle: space (default)

# bad
'a'\
'b'  \
'c'

# good
'a' \
'b' \
'c'

EnforcedStyle: no_space

# bad
'a' \
'b'  \
'c'

# good
'a'\
'b'\
'c'

Configurable attributes

Name Default value Configurable values

EnforcedStyle

space

space, no_space

Layout/LineEndStringConcatenationIndentation

Enabled by default Safe Supports autocorrection Version Added Version Changed

Pending

Yes

Always

1.18

-

Checks the indentation of the next line after a line that ends with a string literal and a backslash.

If EnforcedStyle: aligned is set, the concatenated string parts shall be aligned with the first part. There are some exceptions, such as implicit return values, where the concatenated string parts shall be indented regardless of EnforcedStyle configuration.

If EnforcedStyle: indented is set, it’s the second line that shall be indented one step more than the first line. Lines 3 and forward shall be aligned with line 2.

Examples

# bad
def some_method
  'x' \
  'y' \
  'z'
end

my_hash = {
  first: 'a message' \
    'in two parts'
}

# good
def some_method
  'x' \
    'y' \
    'z'
end

EnforcedStyle: aligned (default)

# bad
puts 'x' \
  'y'

my_hash = {
  first: 'a message' \
    'in two parts'
}

# good
puts 'x' \
     'y'

my_hash = {
  first: 'a message' \
         'in two parts'
}

EnforcedStyle: indented

# bad
result = 'x' \
         'y'

my_hash = {
  first: 'a message' \
         'in two parts'
}

# good
result = 'x' \
  'y'

my_hash = {
  first: 'a message' \
    'in two parts'
}

Configurable attributes

Name Default value Configurable values

EnforcedStyle

aligned

aligned, indented

IndentationWidth

<none>

Integer

Layout/LineLength

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.25

1.4

Checks the length of lines in the source code. The maximum length is configurable. The tab size is configured in the IndentationWidth of the Layout/IndentationStyle cop. It also ignores a shebang line by default.

This cop has some autocorrection capabilities. It can programmatically shorten certain long lines by inserting line breaks into expressions that can be safely split across lines. These include arrays, hashes, and method calls with argument lists.

If autocorrection is enabled, the following cops are recommended to further format the broken lines. (Many of these are enabled by default.)

  • Layout/ArgumentAlignment

  • Layout/ArrayAlignment

  • Layout/BlockAlignment

  • Layout/BlockEndNewline

  • Layout/ClosingParenthesisIndentation

  • Layout/FirstArgumentIndentation

  • Layout/FirstArrayElementIndentation

  • Layout/FirstHashElementIndentation

  • Layout/FirstParameterIndentation

  • Layout/HashAlignment

  • Layout/IndentationWidth

  • Layout/MultilineArrayLineBreaks

  • Layout/MultilineBlockLayout

  • Layout/MultilineHashBraceLayout

  • Layout/MultilineHashKeyLineBreaks

  • Layout/MultilineMethodArgumentLineBreaks

  • Layout/MultilineMethodParameterLineBreaks

  • Layout//ParameterAlignment

  • Style/BlockDelimiters

Together, these cops will pretty print hashes, arrays, method calls, etc. For example, let’s say the max columns is 25:

Examples

# bad
{foo: "0000000000", bar: "0000000000", baz: "0000000000"}

# good
{foo: "0000000000",
bar: "0000000000", baz: "0000000000"}

# good (with recommended cops enabled)
{
  foo: "0000000000",
  bar: "0000000000",
  baz: "0000000000",
}

Configurable attributes

Name Default value Configurable values

Max

120

Integer

AllowHeredoc

true

Boolean

AllowURI

true

Boolean

URISchemes

http, https

Array

IgnoreCopDirectives

true

Boolean

AllowedPatterns

[]

Array

Layout/MultilineArrayBraceLayout

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks that the closing brace in an array literal is either on the same line as the last array element or on a new line.

When using the symmetrical (default) style:

If an array’s opening brace is on the same line as the first element of the array, then the closing brace should be on the same line as the last element of the array.

If an array’s opening brace is on the line above the first element of the array, then the closing brace should be on the line below the last element of the array.

When using the new_line style:

The closing brace of a multi-line array literal must be on the line after the last element of the array.

When using the same_line style:

The closing brace of a multi-line array literal must be on the same line as the last element of the array.

Examples

EnforcedStyle: symmetrical (default)

# bad
[ :a,
  :b
]

# bad
[
  :a,
  :b ]

# good
[ :a,
  :b ]

# good
[
  :a,
  :b
]

EnforcedStyle: new_line

# bad
[
  :a,
  :b ]

# bad
[ :a,
  :b ]

# good
[ :a,
  :b
]

# good
[
  :a,
  :b
]

EnforcedStyle: same_line

# bad
[ :a,
  :b
]

# bad
[
  :a,
  :b
]

# good
[
  :a,
  :b ]

# good
[ :a,
  :b ]

Configurable attributes

Name Default value Configurable values

EnforcedStyle

symmetrical

symmetrical, new_line, same_line

Layout/MultilineArrayLineBreaks

Enabled by default Safe Supports autocorrection Version Added Version Changed

Disabled

Yes

Always

0.67

-

Ensures that each item in a multi-line array starts on a separate line.

Examples

# bad
[
  a, b,
  c
]

# good
[
  a,
  b,
  c
]

# good
[
  a,
  b,
  foo(
    bar
  )
]

AllowMultilineFinalElement: false (default)

# bad
[a, b, foo(
  bar
)]

AllowMultilineFinalElement: true

# good
[a, b, foo(
  bar
)]

Configurable attributes

Name Default value Configurable values

AllowMultilineFinalElement

false

Boolean

Layout/MultilineAssignmentLayout

Enabled by default Safe Supports autocorrection Version Added Version Changed

Disabled

Yes

Always

0.49

-

Checks whether the multiline assignments have a newline after the assignment operator.

Examples

EnforcedStyle: new_line (default)

# bad
foo = if expression
  'bar'
end

# good
foo =
  if expression
    'bar'
  end

# good
foo =
  begin
    compute
  rescue => e
    nil
  end

EnforcedStyle: same_line

# good
foo = if expression
  'bar'
end

SupportedTypes: ['block', 'case', 'class', 'if', 'kwbegin', 'module'] (default)

# good
foo =
  if expression
    'bar'
  end

# good
foo =
  [1].map do |i|
    i + 1
  end

SupportedTypes: ['block']

# good
foo = if expression
  'bar'
end

# good
foo =
  [1].map do |i|
    'bar' * i
  end

Configurable attributes

Name Default value Configurable values

EnforcedStyle

new_line

same_line, new_line

Layout/MultilineBlockLayout

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks whether the multiline do end blocks have a newline after the start of the block. Additionally, it checks whether the block arguments, if any, are on the same line as the start of the block. Putting block arguments on separate lines, because the whole line would otherwise be too long, is accepted.

Examples

# bad
blah do |i| foo(i)
  bar(i)
end

# bad
blah do
  |i| foo(i)
  bar(i)
end

# good
blah do |i|
  foo(i)
  bar(i)
end

# bad
blah { |i| foo(i)
  bar(i)
}

# good
blah { |i|
  foo(i)
  bar(i)
}

# good
blah { |
  long_list,
  of_parameters,
  that_would_not,
  fit_on_one_line
|
  foo(i)
  bar(i)
}

Layout/MultilineHashBraceLayout

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks that the closing brace in a hash literal is either on the same line as the last hash element, or a new line.

When using the symmetrical (default) style:

If a hash’s opening brace is on the same line as the first element of the hash, then the closing brace should be on the same line as the last element of the hash.

If a hash’s opening brace is on the line above the first element of the hash, then the closing brace should be on the line below the last element of the hash.

When using the new_line style:

The closing brace of a multi-line hash literal must be on the line after the last element of the hash.

When using the same_line style:

The closing brace of a multi-line hash literal must be on the same line as the last element of the hash.

Examples

EnforcedStyle: symmetrical (default)

# bad
{ a: 1,
  b: 2
}
# bad
{
  a: 1,
  b: 2 }

# good
{ a: 1,
  b: 2 }

# good
{
  a: 1,
  b: 2
}

EnforcedStyle: new_line

# bad
{
  a: 1,
  b: 2 }

# bad
{ a: 1,
  b: 2 }

# good
{ a: 1,
  b: 2
}

# good
{
  a: 1,
  b: 2
}

EnforcedStyle: same_line

# bad
{ a: 1,
  b: 2
}

# bad
{
  a: 1,
  b: 2
}

# good
{
  a: 1,
  b: 2 }

# good
{ a: 1,
  b: 2 }

Configurable attributes

Name Default value Configurable values

EnforcedStyle

symmetrical

symmetrical, new_line, same_line

Layout/MultilineHashKeyLineBreaks

Enabled by default Safe Supports autocorrection Version Added Version Changed

Disabled

Yes

Always

0.67

-

Ensures that each key in a multi-line hash starts on a separate line.

Examples

# bad
{
  a: 1, b: 2,
  c: 3
}

# good
{
  a: 1,
  b: 2,
  c: 3
}

# good
{
  a: 1,
  b: {
    c: 3,
  }
}

AllowMultilineFinalElement: false (default)

# bad
{ a: 1, b: {
  c: 3,
}}

AllowMultilineFinalElement: true

# good
{ a: 1, b: {
  c: 3,
}}

Configurable attributes

Name Default value Configurable values

AllowMultilineFinalElement

false

Boolean

Layout/MultilineMethodArgumentLineBreaks

Enabled by default Safe Supports autocorrection Version Added Version Changed

Disabled

Yes

Always

0.67

-

Ensures that each argument in a multi-line method call starts on a separate line.

This cop does not move the first argument, if you want that to be on a separate line, see Layout/FirstMethodArgumentLineBreak.

Examples

# bad
foo(a, b,
  c
)

# bad
foo(a, b, {
  foo: "bar",
})

# good
foo(
  a,
  b,
  c
)

# good
foo(a, b, c)

AllowMultilineFinalElement: false (default)

# good
foo(
  a,
  b,
  {
    foo: "bar",
  }
)

AllowMultilineFinalElement: true

# good
foo(
  a,
  b,
  {
    foo: "bar",
  }
)

Configurable attributes

Name Default value Configurable values

AllowMultilineFinalElement

false

Boolean

Layout/MultilineMethodCallBraceLayout

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks that the closing brace in a method call is either on the same line as the last method argument, or a new line.

When using the symmetrical (default) style:

If a method call’s opening brace is on the same line as the first argument of the call, then the closing brace should be on the same line as the last argument of the call.

If an method call’s opening brace is on the line above the first argument of the call, then the closing brace should be on the line below the last argument of the call.

When using the new_line style:

The closing brace of a multi-line method call must be on the line after the last argument of the call.

When using the same_line style:

The closing brace of a multi-line method call must be on the same line as the last argument of the call.

Examples

EnforcedStyle: symmetrical (default)

# bad
foo(a,
  b
)

# bad
foo(
  a,
  b)

# good
foo(a,
  b)

# good
foo(
  a,
  b
)

EnforcedStyle: new_line

# bad
foo(
  a,
  b)

# bad
foo(a,
  b)

# good
foo(a,
  b
)

# good
foo(
  a,
  b
)

EnforcedStyle: same_line

# bad
foo(a,
  b
)

# bad
foo(
  a,
  b
)

# good
foo(
  a,
  b)

# good
foo(a,
  b)

Configurable attributes

Name Default value Configurable values

EnforcedStyle

symmetrical

symmetrical, new_line, same_line

Layout/MultilineMethodCallIndentation

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks the indentation of the method name part in method calls that span more than one line.

Examples

EnforcedStyle: aligned (default)

# bad
while myvariable
.b
  # do something
end

# good
while myvariable
      .b
  # do something
end

# good
Thing.a
     .b
     .c

EnforcedStyle: indented

# good
while myvariable
  .b

  # do something
end

EnforcedStyle: indented_relative_to_receiver

# good
while myvariable
        .a
        .b

  # do something
end

# good
myvariable = Thing
               .a
               .b
               .c

Configurable attributes

Name Default value Configurable values

EnforcedStyle

aligned

aligned, indented, indented_relative_to_receiver

IndentationWidth

<none>

Integer

Layout/MultilineMethodDefinitionBraceLayout

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks that the closing brace in a method definition is either on the same line as the last method parameter, or a new line.

When using the symmetrical (default) style:

If a method definition’s opening brace is on the same line as the first parameter of the definition, then the closing brace should be on the same line as the last parameter of the definition.

If an method definition’s opening brace is on the line above the first parameter of the definition, then the closing brace should be on the line below the last parameter of the definition.

When using the new_line style:

The closing brace of a multi-line method definition must be on the line after the last parameter of the definition.

When using the same_line style:

The closing brace of a multi-line method definition must be on the same line as the last parameter of the definition.

Examples

EnforcedStyle: symmetrical (default)

# bad
def foo(a,
  b
)
end

# bad
def foo(
  a,
  b)
end

# good
def foo(a,
  b)
end

# good
def foo(
  a,
  b
)
end

EnforcedStyle: new_line

# bad
def foo(
  a,
  b)
end

# bad
def foo(a,
  b)
end

# good
def foo(a,
  b
)
end

# good
def foo(
  a,
  b
)
end

EnforcedStyle: same_line

# bad
def foo(a,
  b
)
end

# bad
def foo(
  a,
  b
)
end

# good
def foo(
  a,
  b)
end

# good
def foo(a,
  b)
end

Configurable attributes

Name Default value Configurable values

EnforcedStyle

symmetrical

symmetrical, new_line, same_line

Layout/MultilineMethodParameterLineBreaks

Enabled by default Safe Supports autocorrection Version Added Version Changed

Disabled

Yes

Always

1.32

-

Ensures that each parameter in a multi-line method definition starts on a separate line.

This cop does not move the first argument, if you want that to be on a separate line, see Layout/FirstMethodParameterLineBreak.

Examples

# bad
def foo(a, b,
  c
)
end

# good
def foo(
  a,
  b,
  c
)
end

# good
def foo(
  a,
  b = {
    foo: "bar",
  }
)
end

# good
def foo(a, b, c)
end

AllowMultilineFinalElement: false (default)

# bad
def foo(a, b = {
  foo: "bar",
})
end

AllowMultilineFinalElement: true

# good
def foo(a, b = {
  foo: "bar",
})
end

Configurable attributes

Name Default value Configurable values

AllowMultilineFinalElement

false

Boolean

Layout/MultilineOperationIndentation

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks the indentation of the right hand side operand in binary operations that span more than one line.

The aligned style checks that operators are aligned if they are part of an if or while condition, an explicit return statement, etc. In other contexts, the second operand should be indented regardless of enforced style.

Examples

EnforcedStyle: aligned (default)

# bad
if a +
    b
  something &&
  something_else
end

# good
if a +
   b
  something &&
    something_else
end

EnforcedStyle: indented

# bad
if a +
   b
  something &&
  something_else
end

# good
if a +
    b
  something &&
    something_else
end

Configurable attributes

Name Default value Configurable values

EnforcedStyle

aligned

aligned, indented

IndentationWidth

<none>

Integer

Layout/ParameterAlignment

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

0.77

Here we check if the parameters on a multi-line method call or definition are aligned.

To set the alignment of the first argument, use the cop FirstParameterIndentation.

Examples

EnforcedStyle: with_first_parameter (default)

# good

def foo(bar,
        baz)
  123
end

def foo(
  bar,
  baz
)
  123
end

# bad

def foo(bar,
     baz)
  123
end

# bad

def foo(
  bar,
     baz)
  123
end

EnforcedStyle: with_fixed_indentation

# good

def foo(bar,
  baz)
  123
end

def foo(
  bar,
  baz
)
  123
end

# bad

def foo(bar,
        baz)
  123
end

# bad

def foo(
  bar,
     baz)
  123
end

Configurable attributes

Name Default value Configurable values

EnforcedStyle

with_first_parameter

with_first_parameter, with_fixed_indentation

IndentationWidth

<none>

Integer

Layout/RedundantLineBreak

Enabled by default Safe Supports autocorrection Version Added Version Changed

Disabled

Yes

Always

1.13

-

Checks whether certain expressions, e.g. method calls, that could fit completely on a single line, are broken up into multiple lines unnecessarily.

Examples

any configuration

# bad
foo(
  a,
  b
)

puts 'string that fits on ' \
     'a single line'

things
  .select { |thing| thing.cond? }
  .join('-')

# good
foo(a, b)

puts 'string that fits on a single line'

things.select { |thing| thing.cond? }.join('-')

InspectBlocks: false (default)

# good
foo(a) do |x|
  puts x
end

InspectBlocks: true

# bad
foo(a) do |x|
  puts x
end

# good
foo(a) { |x| puts x }

Configurable attributes

Name Default value Configurable values

InspectBlocks

false

Boolean

Layout/RescueEnsureAlignment

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks whether the rescue and ensure keywords are aligned properly.

Examples

# bad
begin
  something
  rescue
  puts 'error'
end

# good
begin
  something
rescue
  puts 'error'
end

Layout/SingleLineBlockChain

Enabled by default Safe Supports autocorrection Version Added Version Changed

Disabled

Yes

Always

1.14

-

Checks if method calls are chained onto single line blocks. It considers that a line break before the dot improves the readability of the code.

Examples

# bad
example.select { |item| item.cond? }.join('-')

# good
example.select { |item| item.cond? }
       .join('-')

# good (not a concern for this cop)
example.select do |item|
  item.cond?
end.join('-')

Layout/SpaceAfterColon

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks for colon (:) not followed by some kind of space. N.B. this cop does not handle spaces after a ternary operator, which are instead handled by Layout/SpaceAroundOperators.

Examples

# bad
def f(a:, b:2); {a:3}; end

# good
def f(a:, b: 2); {a: 3}; end

Layout/SpaceAfterComma

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks for comma (,) not followed by some kind of space.

Examples

# bad
[1,2]
{ foo:bar,}

# good
[1, 2]
{ foo:bar, }

Layout/SpaceAfterMethodName

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks for space between a method name and a left parenthesis in defs.

Examples

# bad
def func (x) end
def method= (y) end

# good
def func(x) end
def method=(y) end

Layout/SpaceAfterNot

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks for space after !.

Examples

# bad
! something

# good
!something

Layout/SpaceAfterSemicolon

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks for semicolon (;) not followed by some kind of space.

Examples

# bad
x = 1;y = 2

# good
x = 1; y = 2

Layout/SpaceAroundBlockParameters

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks the spacing inside and after block parameters pipes. Line breaks inside parameter pipes are checked by Layout/MultilineBlockLayout and not by this cop.

Examples

EnforcedStyleInsidePipes: no_space (default)

# bad
{}.each { | x,  y |puts x }
->( x,  y ) { puts x }

# good
{}.each { |x, y| puts x }
->(x, y) { puts x }

EnforcedStyleInsidePipes: space

# bad
{}.each { |x,  y| puts x }
->(x,  y) { puts x }

# good
{}.each { | x, y | puts x }
->( x, y ) { puts x }

Configurable attributes

Name Default value Configurable values

EnforcedStyleInsidePipes

no_space

space, no_space

Layout/SpaceAroundEqualsInParameterDefault

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks that the equals signs in parameter default assignments have or don’t have surrounding space depending on configuration.

Examples

EnforcedStyle: space (default)

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

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

EnforcedStyle: no_space

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

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

Configurable attributes

Name Default value Configurable values

EnforcedStyle

space

space, no_space

Layout/SpaceAroundKeyword

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks the spacing around the keywords.

Examples

# bad
something 'test'do|x|
end

while(something)
end

something = 123if test

# good
something 'test' do |x|
end

while (something)
end

something = 123 if test

Layout/SpaceAroundMethodCallOperator

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.82

-

Checks method call operators to not have spaces around them.

Examples

# bad
foo. bar
foo .bar
foo . bar
foo. bar .buzz
foo
  . bar
  . buzz
foo&. bar
foo &.bar
foo &. bar
foo &. bar&. buzz
RuboCop:: Cop
RuboCop:: Cop:: Base
:: RuboCop::Cop

# good
foo.bar
foo.bar.buzz
foo
  .bar
  .buzz
foo&.bar
foo&.bar&.buzz
RuboCop::Cop
RuboCop::Cop::Base
::RuboCop::Cop

Layout/SpaceAroundOperators

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks that operators have space around them, except for ** which should or shouldn’t have surrounding space depending on configuration. It allows vertical alignment consisting of one or more whitespace around operators.

This cop has AllowForAlignment option. When true, allows most uses of extra spacing if the intent is to align with an operator on the previous or next line, not counting empty lines or comment lines.

Examples

# bad
total = 3*4
"apple"+"juice"
my_number = 38/4

# good
total = 3 * 4
"apple" + "juice"
my_number = 38 / 4

AllowForAlignment: true (default)

# good
{
  1 =>  2,
  11 => 3
}

AllowForAlignment: false

# bad
{
  1 =>  2,
  11 => 3
}

EnforcedStyleForExponentOperator: no_space (default)

# bad
a ** b

# good
a**b

EnforcedStyleForExponentOperator: space

# bad
a**b

# good
a ** b

EnforcedStyleForRationalLiterals: no_space (default)

# bad
1 / 48r

# good
1/48r

EnforcedStyleForRationalLiterals: space

# bad
1/48r

# good
1 / 48r

Configurable attributes

Name Default value Configurable values

AllowForAlignment

true

Boolean

EnforcedStyleForExponentOperator

no_space

space, no_space

EnforcedStyleForRationalLiterals

no_space

space, no_space

Layout/SpaceBeforeBlockBraces

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

0.52

Checks that block braces have or don’t have a space before the opening brace depending on configuration.

Examples

EnforcedStyle: space (default)

# bad
foo.map{ |a|
  a.bar.to_s
}

# good
foo.map { |a|
  a.bar.to_s
}

EnforcedStyle: no_space

# bad
foo.map { |a|
  a.bar.to_s
}

# good
foo.map{ |a|
  a.bar.to_s
}

EnforcedStyleForEmptyBraces: space (default)

# bad
7.times{}

# good
7.times {}

EnforcedStyleForEmptyBraces: no_space

# bad
7.times {}

# good
7.times{}

Configurable attributes

Name Default value Configurable values

EnforcedStyle

space

space, no_space

EnforcedStyleForEmptyBraces

space

space, no_space

Layout/SpaceBeforeBrackets

Enabled by default Safe Supports autocorrection Version Added Version Changed

Pending

Yes

Always

1.7

-

Checks for space between the name of a receiver and a left brackets.

Examples

# bad
collection [index_or_key]

# good
collection[index_or_key]

Layout/SpaceBeforeComma

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks for comma (,) preceded by space.

Examples

# bad
[1 , 2 , 3]
a(1 , 2)
each { |a , b| }

# good
[1, 2, 3]
a(1, 2)
each { |a, b| }

Layout/SpaceBeforeComment

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks for missing space between a token and a comment on the same line.

Examples

# bad
1 + 1# this operation does ...

# good
1 + 1 # this operation does ...

Layout/SpaceBeforeFirstArg

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks that exactly one space is used between a method name and the first argument for method calls without parentheses.

Alternatively, extra spaces can be added to align the argument with something on a preceding or following line, if the AllowForAlignment config parameter is true.

Examples

# bad
something  x
something   y, z
something'hello'

# good
something x
something y, z
something 'hello'

Configurable attributes

Name Default value Configurable values

AllowForAlignment

true

Boolean

Layout/SpaceBeforeSemicolon

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks for semicolon (;) preceded by space.

Examples

# bad
x = 1 ; y = 2

# good
x = 1; y = 2

Layout/SpaceInLambdaLiteral

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks for spaces between and opening parameter parenthesis (() in lambda literals.

Examples

EnforcedStyle: require_no_space (default)

# bad
a = -> (x, y) { x + y }

# good
a = ->(x, y) { x + y }

EnforcedStyle: require_space

# bad
a = ->(x, y) { x + y }

# good
a = -> (x, y) { x + y }

Configurable attributes

Name Default value Configurable values

EnforcedStyle

require_no_space

require_no_space, require_space

Layout/SpaceInsideArrayLiteralBrackets

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.52

-

Checks that brackets used for array literals have or don’t have surrounding space depending on configuration.

Examples

EnforcedStyle: no_space (default)

# The `no_space` style enforces that array literals have
# no surrounding space.

# bad
array = [ a, b, c, d ]

# good
array = [a, b, c, d]

EnforcedStyle: space

# The `space` style enforces that array literals have
# surrounding space.

# bad
array = [a, b, c, d]

# good
array = [ a, b, c, d ]

EnforcedStyle: compact

# The `compact` style normally requires a space inside
# array brackets, with the exception that successive left
# or right brackets are collapsed together in nested arrays.

# bad
array = [ a, [ b, c ] ]
array = [
  [ a ],
  [ b, c ]
]

# good
array = [ a, [ b, c ]]
array = [[ a ],
  [ b, c ]]

EnforcedStyleForEmptyBrackets: no_space (default)

# The `no_space` EnforcedStyleForEmptyBrackets style enforces that
# empty array brackets do not contain spaces.

# bad
foo = [ ]
bar = [     ]

# good
foo = []
bar = []

EnforcedStyleForEmptyBrackets: space

# The `space` EnforcedStyleForEmptyBrackets style enforces that
# empty array brackets contain exactly one space.

# bad
foo = []
bar = [    ]

# good
foo = [ ]
bar = [ ]

Configurable attributes

Name Default value Configurable values

EnforcedStyle

no_space

space, no_space, compact

EnforcedStyleForEmptyBrackets

no_space

space, no_space

Layout/SpaceInsideArrayPercentLiteral

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks for unnecessary additional spaces inside array percent literals (i.e. %i/%w).

Note that blank percent literals (e.g. %i( )) are checked by Layout/SpaceInsidePercentLiteralDelimiters.

Examples

# bad
%w(foo  bar  baz)
# good
%i(foo bar baz)

Layout/SpaceInsideBlockBraces

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks that block braces have or don’t have surrounding space inside them on configuration. For blocks taking parameters, it checks that the left brace has or doesn’t have trailing space depending on configuration.

Examples

EnforcedStyle: space (default)

# The `space` style enforces that block braces have
# surrounding space.

# bad
some_array.each {puts e}

# good
some_array.each { puts e }

EnforcedStyle: no_space

# The `no_space` style enforces that block braces don't
# have surrounding space.

# bad
some_array.each { puts e }

# good
some_array.each {puts e}

EnforcedStyleForEmptyBraces: no_space (default)

# The `no_space` EnforcedStyleForEmptyBraces style enforces that
# block braces don't have a space in between when empty.

# bad
some_array.each {   }
some_array.each {  }
some_array.each { }

# good
some_array.each {}

EnforcedStyleForEmptyBraces: space

# The `space` EnforcedStyleForEmptyBraces style enforces that
# block braces have at least a space in between when empty.

# bad
some_array.each {}

# good
some_array.each { }
some_array.each {  }
some_array.each {   }

SpaceBeforeBlockParameters: true (default)

# The SpaceBeforeBlockParameters style set to `true` enforces that
# there is a space between `{` and `|`. Overrides `EnforcedStyle`
# if there is a conflict.

# bad
[1, 2, 3].each {|n| n * 2 }

# good
[1, 2, 3].each { |n| n * 2 }

SpaceBeforeBlockParameters: false

# The SpaceBeforeBlockParameters style set to `false` enforces that
# there is no space between `{` and `|`. Overrides `EnforcedStyle`
# if there is a conflict.

# bad
[1, 2, 3].each { |n| n * 2 }

# good
[1, 2, 3].each {|n| n * 2 }

Configurable attributes

Name Default value Configurable values

EnforcedStyle

space

space, no_space

EnforcedStyleForEmptyBraces

no_space

space, no_space

SpaceBeforeBlockParameters

true

Boolean

Layout/SpaceInsideHashLiteralBraces

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks that braces used for hash literals have or don’t have surrounding space depending on configuration.

Examples

EnforcedStyle: space (default)

# The `space` style enforces that hash literals have
# surrounding space.

# bad
h = {a: 1, b: 2}

# good
h = { a: 1, b: 2 }

EnforcedStyle: no_space

# The `no_space` style enforces that hash literals have
# no surrounding space.

# bad
h = { a: 1, b: 2 }

# good
h = {a: 1, b: 2}

EnforcedStyle: compact

# The `compact` style normally requires a space inside
# hash braces, with the exception that successive left
# braces or right braces are collapsed together in nested hashes.

# bad
h = { a: { b: 2 } }
foo = { { a: 1 } => { b: { c: 2 } } }

# good
h = { a: { b: 2 }}
foo = {{ a: 1 } => { b: { c: 2 }}}

EnforcedStyleForEmptyBraces: no_space (default)

# The `no_space` EnforcedStyleForEmptyBraces style enforces that
# empty hash braces do not contain spaces.

# bad
foo = { }
bar = {    }
baz = {
}

# good
foo = {}
bar = {}
baz = {}

EnforcedStyleForEmptyBraces: space

# The `space` EnforcedStyleForEmptyBraces style enforces that
# empty hash braces contain space.

# bad
foo = {}

# good
foo = { }
foo = {    }
foo = {
}

Configurable attributes

Name Default value Configurable values

EnforcedStyle

space

space, no_space, compact

EnforcedStyleForEmptyBraces

no_space

space, no_space

Layout/SpaceInsideParens

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

1.22

Checks for spaces inside ordinary round parentheses.

Examples

EnforcedStyle: no_space (default)

# The `no_space` style enforces that parentheses do not have spaces.

# bad
f( 3)
g = (a + 3 )
f( )

# good
f(3)
g = (a + 3)
f()

EnforcedStyle: space

# The `space` style enforces that parentheses have a space at the
# beginning and end.
# Note: Empty parentheses should not have spaces.

# bad
f(3)
g = (a + 3)
y( )

# good
f( 3 )
g = ( a + 3 )
y()

EnforcedStyle: compact

# The `compact` style enforces that parentheses have a space at the
# beginning with the exception that successive parentheses are allowed.
# Note: Empty parentheses should not have spaces.

# bad
f(3)
g = (a + 3)
y( )
g( f( x ) )
g( f( x( 3 ) ), 5 )
g( ( ( 3 + 5 ) * f) ** x, 5 )

# good
f( 3 )
g = ( a + 3 )
y()
g( f( x ))
g( f( x( 3 )), 5 )
g((( 3 + 5 ) * f ) ** x, 5 )

Configurable attributes

Name Default value Configurable values

EnforcedStyle

no_space

space, compact, no_space

Layout/SpaceInsidePercentLiteralDelimiters

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks for unnecessary additional spaces inside the delimiters of %i/%w/%x literals.

Examples

# bad
%i( foo bar baz )

# good
%i(foo bar baz)

# bad
%w( foo bar baz )

# good
%w(foo bar baz)

# bad
%x(  ls -l )

# good
%x(ls -l)

# bad
%w( )
%w(
)

# good
%w()

Layout/SpaceInsideRangeLiteral

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks for spaces inside range literals.

Examples

# bad
1 .. 3

# good
1..3

# bad
'a' .. 'z'

# good
'a'..'z'

Layout/SpaceInsideReferenceBrackets

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.52

0.53

Checks that reference brackets have or don’t have surrounding space depending on configuration.

Examples

EnforcedStyle: no_space (default)

# The `no_space` style enforces that reference brackets have
# no surrounding space.

# bad
hash[ :key ]
array[ index ]

# good
hash[:key]
array[index]

EnforcedStyle: space

# The `space` style enforces that reference brackets have
# surrounding space.

# bad
hash[:key]
array[index]

# good
hash[ :key ]
array[ index ]

EnforcedStyleForEmptyBrackets: no_space (default)

# The `no_space` EnforcedStyleForEmptyBrackets style enforces that
# empty reference brackets do not contain spaces.

# bad
foo[ ]
foo[     ]
foo[
]

# good
foo[]

EnforcedStyleForEmptyBrackets: space

# The `space` EnforcedStyleForEmptyBrackets style enforces that
# empty reference brackets contain exactly one space.

# bad
foo[]
foo[    ]
foo[
]

# good
foo[ ]

Configurable attributes

Name Default value Configurable values

EnforcedStyle

no_space

space, no_space

EnforcedStyleForEmptyBrackets

no_space

space, no_space

Layout/SpaceInsideStringInterpolation

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

-

Checks for whitespace within string interpolations.

Examples

EnforcedStyle: no_space (default)

# bad
   var = "This is the #{ space } example"

# good
   var = "This is the #{no_space} example"

EnforcedStyle: space

# bad
   var = "This is the #{no_space} example"

# good
   var = "This is the #{ space } example"

Configurable attributes

Name Default value Configurable values

EnforcedStyle

no_space

space, no_space

Layout/TrailingEmptyLines

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

0.77

Looks for trailing blank lines and a final newline in the source code.

Examples

EnforcedStyle: final_newline (default)

# `final_newline` looks for one newline at the end of files.

# bad
class Foo; end

# EOF

# bad
class Foo; end # EOF

# good
class Foo; end
# EOF

EnforcedStyle: final_blank_line

# `final_blank_line` looks for one blank line followed by a new line
# at the end of files.

# bad
class Foo; end
# EOF

# bad
class Foo; end # EOF

# good
class Foo; end

# EOF

Configurable attributes

Name Default value Configurable values

EnforcedStyle

final_newline

final_newline, final_blank_line

Layout/TrailingWhitespace

Enabled by default Safe Supports autocorrection Version Added Version Changed

Enabled

Yes

Always

0.49

1.0

Looks for trailing whitespace in the source code.

Examples

# The line in this example contains spaces after the 0.
# bad
x = 0

# The line in this example ends directly after the 0.
# good
x = 0

AllowInHeredoc: false (default)

# The line in this example contains spaces after the 0.
# bad
code = <<~RUBY
  x = 0
RUBY

# ok
code = <<~RUBY
  x = 0 #{}
RUBY

# good
trailing_whitespace = ' '
code = <<~RUBY
  x = 0#{trailing_whitespace}
RUBY

AllowInHeredoc: true

# The line in this example contains spaces after the 0.
# good
code = <<~RUBY
  x = 0
RUBY

Configurable attributes

Name Default value Configurable values

AllowInHeredoc

false

Boolean

AllowMultilineFinalElement

AllowMultilineFinalElement is a boolean option (false by default) that is available on the following Layout cops:

  • FirstArrayElementLineBreak

  • FirstHashElementLineBreak

  • FirstMethodArgumentLineBreak

  • FirstMethodParameterLineBreak

  • MultilineArrayLineBreaks

  • MultilineHashKeyLineBreaks

  • MultilineMethodArgumentLineBreaks

  • MultilineMethodParameterLineBreaks

Those cops ignore their respective expressions if all or the elements of the expression are on the same line. If AllowMultilineFinalElement is set to true, the cop will also ignore multiline expressions if the last element starts on the same line, but ends on a different one.

This works well with Layout/LineLength to present elements on individual lines when wrapping, while not affecting expressions that are already short enough, and only considered multiline because of their last element.

Each cop can be configured independently allowing for more fine-grained control over what is considered good ok in the codebase.

Examples

Here are some examples of real world expressions that get wrapped by their respective cops, but that are considered ok when setting AllowMultilineFinalElement to true on those same cops.

# good

# FirstArrayElementLineBreak and MultilineArrayLineBreaks

# Array of error containing a single error
errors = [{
  error: "Something went wrong",
  error_code: error_code,
}]

# Array of flags, with last flag computed
flags = [:a, :b, foo(
  bar,
  baz
)]

# FirstHashElementLineBreak and MultilineHashKeyLineBreaks
hash = { foo: 1, bar: 2, baz: {
  c: 1,
  d: 2
}}

# FirstMethodArgumentLineBreak and MultilineMethodArgumentLineBreaks
single_argument_hash_method_call({
  a: 1,
  b: 2,
  c: 3
})

# Call some method, with a long last argument, that is a hash
write_log(:error,  {
  "job_class" => job.class.name,
  "resource" => resource.id,
  "message" => "Something wrong happened here",
})

# Rails before action with long last argument
before_action :load_something, only: [
  :show,
  :list,
  :some_other_long_action_name,
]

# Rails validation with inline callback
validate :name, presence: true, on: [:create, :activate], if: -> {
  active? && some_relationship.any?
}

# Rails after commit hook, with some Sorbet bindings
after_commit :geolocate, unless: -> {
  T.bind(self, Address)
  archived? || invalid?
}

# FirstMethodParameterLineBreak and MultilineMethodParameterLineBreaks

# Method with a long last parameter default value
def foo(foo, bar, baz = {
  a: 1,
  b: 2,
  c: 3
})
  do_something
end