Class: RuboCop::Cop::Performance::ReverseFirst

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
RangeHelp
Defined in:
lib/rubocop/cop/performance/reverse_first.rb

Overview

Identifies places where ‘reverse.first(n)` and `reverse.first` can be replaced by `last(n).reverse` and `last`.

Examples:


# bad
array.reverse.first(5)
array.reverse.first

# good
array.last(5).reverse
array.last

Constant Summary collapse

MSG =
'Use `%<good_method>s` instead of `%<bad_method>s`.'
RESTRICT_ON_SEND =
%i[first].freeze

Instance Method Summary collapse

Instance Method Details

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



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/rubocop/cop/performance/reverse_first.rb', line 30

def on_send(node)
  reverse_first_candidate?(node) do |receiver|
    range = correction_range(receiver, node)
    message = build_message(node, range)

    add_offense(range, message: message) do |corrector|
      replacement = build_good_method(node)

      corrector.replace(range, replacement)
    end
  end
end