Class: RuboCop::Cop::Performance::ArraySemiInfiniteRangeSlice

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

Overview

Identifies places where slicing arrays with semi-infinite ranges can be replaced by ‘Array#take` and `Array#drop`. This cop was created due to a mistake in microbenchmark and hence is disabled by default. Refer github.com/rubocop/rubocop-performance/pull/175#issuecomment-731892717

Examples:

# bad
array[..2]
array[...2]
array[2..]
array[2...]
array.slice(..2)

# good
array.take(3)
array.take(2)
array.drop(2)
array.drop(2)
array.take(3)

Constant Summary collapse

MSG =
'Use `%<prefer>s` instead of `%<current>s` with semi-infinite range.'
SLICE_METHODS =
Set[:[], :slice].freeze
RESTRICT_ON_SEND =
SLICE_METHODS

Instance Method Summary collapse

Instance Method Details

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



52
53
54
55
56
57
58
59
60
61
# File 'lib/rubocop/cop/performance/array_semi_infinite_range_slice.rb', line 52

def on_send(node)
  endless_range_slice?(node) do |receiver, method_name, range_node|
    prefer = range_node.begin ? :drop : :take
    message = format(MSG, prefer: prefer, current: method_name)

    add_offense(node, message: message) do |corrector|
      corrector.replace(node, correction(receiver, range_node))
    end
  end
end