Class: RuboCop::Cop::Style::ArrayFirstLast

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/style/array_first_last.rb

Overview

Identifies usages of ‘arr` and `arr` and suggests to change them to use `arr.first` and `arr.last` instead.

The cop is disabled by default due to safety concerns.

Examples:

# bad
arr[0]
arr[-1]

# good
arr.first
arr.last
arr[0] = 2
arr[0][-2]

Constant Summary collapse

MSG =
'Use `%<preferred>s`.'
RESTRICT_ON_SEND =
i[[]].freeze

Instance Method Summary collapse

Methods included from AutoCorrector

support_autocorrect?

Instance Method Details

#on_send(node) ⇒ Object Also known as: on_csend

rubocop:disable Metrics/AbcSize



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/rubocop/cop/style/array_first_last.rb', line 35

def on_send(node)
  return unless node.arguments.size == 1 && node.first_argument.int_type?

  value = node.first_argument.value
  return unless [0, -1].include?(value)

  node = innermost_braces_node(node)
  return if node.parent && brace_method?(node.parent)

  preferred = (value.zero? ? 'first' : 'last')
  offense_range = find_offense_range(node)

  add_offense(offense_range, message: format(MSG, preferred: preferred)) do |corrector|
    corrector.replace(offense_range, preferred_value(node, preferred))
  end
end