Sha256: 265f2022f195d601c54da51ae2582dcc369a9ead4827a4fd8dc1a38e84a68b72

Contents?: true

Size: 1.33 KB

Versions: 20

Compression:

Stored size: 1.33 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # This cop checks that arrays are sliced with endless ranges instead of
      # `ary[start..-1]` on Ruby 2.6+.
      #
      # @safety
      #   This cop is unsafe because `x..-1` and `x..` are only guaranteed to
      #   be equivalent for `Array#[]`, and the cop cannot determine what class
      #   the receiver is.
      #
      #   For example:
      #   [source,ruby]
      #   ----
      #   sum = proc { |ary| ary.sum }
      #   sum[-3..-1] # => -6
      #   sum[-3..] # Hangs forever
      #   ----
      #
      # @example
      #   # bad
      #   items[1..-1]
      #
      #   # good
      #   items[1..]
      class SlicingWithRange < Base
        extend AutoCorrector
        extend TargetRubyVersion

        minimum_target_ruby_version 2.6

        MSG = 'Prefer ary[n..] over ary[n..-1].'
        RESTRICT_ON_SEND = %i[[]].freeze

        # @!method range_till_minus_one?(node)
        def_node_matcher :range_till_minus_one?, '(irange !nil? (int -1))'

        def on_send(node)
          return unless node.arguments.count == 1
          return unless range_till_minus_one?(node.arguments.first)

          add_offense(node.first_argument) do |corrector|
            corrector.remove(node.first_argument.end)
          end
        end
      end
    end
  end
end

Version data entries

20 entries across 20 versions & 4 rubygems

Version Path
scrapbook-0.3.2 vendor/ruby/2.7.0/gems/rubocop-1.26.0/lib/rubocop/cop/style/slicing_with_range.rb
scrapbook-0.3.1 vendor/ruby/2.7.0/gems/rubocop-1.26.0/lib/rubocop/cop/style/slicing_with_range.rb
rubocop-1.29.1 lib/rubocop/cop/style/slicing_with_range.rb
rubocop-1.28.2 lib/rubocop/cop/style/slicing_with_range.rb
rubocop-1.28.1 lib/rubocop/cop/style/slicing_with_range.rb
rubocop-1.28.0 lib/rubocop/cop/style/slicing_with_range.rb
rubocop-1.27.0 lib/rubocop/cop/style/slicing_with_range.rb
rubocop-1.26.1 lib/rubocop/cop/style/slicing_with_range.rb
op_connect-0.1.2 vendor/bundle/ruby/3.1.0/gems/rubocop-1.26.0/lib/rubocop/cop/style/slicing_with_range.rb
rubocop-1.26.0 lib/rubocop/cop/style/slicing_with_range.rb
rubocop-1.25.1 lib/rubocop/cop/style/slicing_with_range.rb
rubocop-1.25.0 lib/rubocop/cop/style/slicing_with_range.rb
phillipug-foodie-0.1.0 .vendor/ruby/3.0.0/gems/rubocop-1.24.0/lib/rubocop/cop/style/slicing_with_range.rb
rubocop-1.24.1 lib/rubocop/cop/style/slicing_with_range.rb
rubocop-1.24.0 lib/rubocop/cop/style/slicing_with_range.rb
rubocop-1.23.0 lib/rubocop/cop/style/slicing_with_range.rb
rubocop-1.22.3 lib/rubocop/cop/style/slicing_with_range.rb
rubocop-1.22.2 lib/rubocop/cop/style/slicing_with_range.rb
rubocop-1.22.1 lib/rubocop/cop/style/slicing_with_range.rb
rubocop-1.22.0 lib/rubocop/cop/style/slicing_with_range.rb