diff --git a/changelog/fix_false_positives_for_performance_array_semi_infinite_range_slice.md b/changelog/fix_false_positives_for_performance_array_semi_infinite_range_slice.md new file mode 100644 index 0000000000..27fa490e5d --- /dev/null +++ b/changelog/fix_false_positives_for_performance_array_semi_infinite_range_slice.md @@ -0,0 +1 @@ +* [#365](https://github.com/rubocop/rubocop-performance/issues/365): Fix false positives for `Performance/ArraySemiInfiniteRangeSlice` when using `[]` with string literals. ([@koic][]) diff --git a/lib/rubocop/cop/performance/array_semi_infinite_range_slice.rb b/lib/rubocop/cop/performance/array_semi_infinite_range_slice.rb index eaee567d77..3658ab3e79 100644 --- a/lib/rubocop/cop/performance/array_semi_infinite_range_slice.rb +++ b/lib/rubocop/cop/performance/array_semi_infinite_range_slice.rb @@ -39,7 +39,7 @@ class ArraySemiInfiniteRangeSlice < Base RESTRICT_ON_SEND = SLICE_METHODS def_node_matcher :endless_range_slice?, <<~PATTERN - (call $_ $%SLICE_METHODS $#endless_range?) + (call $!{str dstr xstr} $%SLICE_METHODS $#endless_range?) PATTERN def_node_matcher :endless_range?, <<~PATTERN diff --git a/spec/rubocop/cop/performance/array_semi_infinite_range_slice_spec.rb b/spec/rubocop/cop/performance/array_semi_infinite_range_slice_spec.rb index fe528119dd..399d299a73 100644 --- a/spec/rubocop/cop/performance/array_semi_infinite_range_slice_spec.rb +++ b/spec/rubocop/cop/performance/array_semi_infinite_range_slice_spec.rb @@ -77,5 +77,23 @@ array[-2..] RUBY end + + it 'does not registers an offense when using `[]` with endless range for string literal' do + expect_no_offenses(<<~RUBY) + 'str'[3..] + RUBY + end + + it 'does not registers an offense when using `[]` with endless range for interpolated string literal' do + expect_no_offenses(<<~'RUBY') + "string#{interpolation}"[3..] + RUBY + end + + it 'does not registers an offense when using `[]` with endless range for backquote string literal' do + expect_no_offenses(<<~RUBY) + `str`[3..] + RUBY + end end end