diff --git a/changelog/fix_false_negative_for_reverse_each.md b/changelog/fix_false_negative_for_reverse_each.md new file mode 100644 index 0000000000..5d943cea0e --- /dev/null +++ b/changelog/fix_false_negative_for_reverse_each.md @@ -0,0 +1 @@ +* [#390](https://github.com/rubocop/rubocop-performance/issues/390): Fix a false negative for `Performance/ReverseEach` when safe navigation is between `reverse` and `each`. ([@fatkodima][]) diff --git a/lib/rubocop/cop/performance/reverse_each.rb b/lib/rubocop/cop/performance/reverse_each.rb index 85f0df2e2f..a846b7a4fb 100644 --- a/lib/rubocop/cop/performance/reverse_each.rb +++ b/lib/rubocop/cop/performance/reverse_each.rb @@ -27,7 +27,7 @@ class ReverseEach < Base RESTRICT_ON_SEND = %i[each].freeze def_node_matcher :reverse_each?, <<~MATCHER - (send (call _ :reverse) :each) + (call (call _ :reverse) :each) MATCHER def on_send(node) diff --git a/spec/rubocop/cop/performance/reverse_each_spec.rb b/spec/rubocop/cop/performance/reverse_each_spec.rb index ab7b0837b6..96f1f91226 100644 --- a/spec/rubocop/cop/performance/reverse_each_spec.rb +++ b/spec/rubocop/cop/performance/reverse_each_spec.rb @@ -15,6 +15,13 @@ RUBY end + it 'registers an offense when each is called on reverse with safe navigation operator chain' do + expect_offense(<<~RUBY) + array&.reverse&.each { |e| puts e } + ^^^^^^^^^^^^^ Use `reverse_each` instead of `reverse.each`. + RUBY + end + it 'registers an offense when each is called on reverse on a variable' do expect_offense(<<~RUBY) arr = [1, 2, 3]