diff --git a/CHANGELOG.md b/CHANGELOG.md index 546bac31128..f6de1dbe930 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ * [#7953](https://github.com/rubocop-hq/rubocop/issues/7953): Fix an error for `Lint/AmbiguousOperator` when a method with no arguments is used in advance. ([@koic][]) * [#7962](https://github.com/rubocop-hq/rubocop/issues/7962): Fix a false positive for `Lint/ParenthesesAsGroupedExpression` when heredoc has a space between the same string as the method name and `(`. ([@koic][]) +* [#7967](https://github.com/rubocop-hq/rubocop/pull/7967): `Style/SlicingWithRange` cop now supports any expression as its first index. ([@zverok][]) ### Changes diff --git a/lib/rubocop/cop/style/slicing_with_range.rb b/lib/rubocop/cop/style/slicing_with_range.rb index 9d8860d40bb..de3769d9b8f 100644 --- a/lib/rubocop/cop/style/slicing_with_range.rb +++ b/lib/rubocop/cop/style/slicing_with_range.rb @@ -19,7 +19,7 @@ class SlicingWithRange < Cop MSG = 'Prefer ary[n..] over ary[n..-1].' - def_node_matcher :range_till_minus_one?, '(irange (int _) (int -1))' + def_node_matcher :range_till_minus_one?, '(irange !nil? (int -1))' def on_send(node) return unless node.method?(:[]) && node.arguments.count == 1 diff --git a/spec/rubocop/cop/style/slicing_with_range_spec.rb b/spec/rubocop/cop/style/slicing_with_range_spec.rb index f72052a5624..7395626a75b 100644 --- a/spec/rubocop/cop/style/slicing_with_range_spec.rb +++ b/spec/rubocop/cop/style/slicing_with_range_spec.rb @@ -23,6 +23,17 @@ RUBY end + it 'reports an offense for slicing from expression to ..-1' do + expect_offense(<<~RUBY) + ary[fetch_start(true).first..-1] + ^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer ary[n..] over ary[n..-1]. + RUBY + + expect_correction(<<~RUBY) + ary[fetch_start(true).first..] + RUBY + end + it 'reports no offense for excluding end' do expect_no_offenses(<<~RUBY) ary[1...-1]