diff --git a/changelog/fix_false_negative_for_performance_chain_array_allocation.md b/changelog/fix_false_negative_for_performance_chain_array_allocation.md new file mode 100644 index 0000000000..622139126a --- /dev/null +++ b/changelog/fix_false_negative_for_performance_chain_array_allocation.md @@ -0,0 +1 @@ +* [#294](https://github.com/rubocop/rubocop-performance/pull/294): Fix a false negative for `Performance/ChainArrayAllocation` when using `array.first(do_something).uniq`. ([@koic][]) diff --git a/lib/rubocop/cop/performance/chain_array_allocation.rb b/lib/rubocop/cop/performance/chain_array_allocation.rb index 84a33f53f7..1c65c96fb3 100644 --- a/lib/rubocop/cop/performance/chain_array_allocation.rb +++ b/lib/rubocop/cop/performance/chain_array_allocation.rb @@ -53,7 +53,7 @@ class ChainArrayAllocation < Base def_node_matcher :chain_array_allocation?, <<~PATTERN (send { - (send _ $%RETURN_NEW_ARRAY_WHEN_ARGS {int lvar ivar cvar gvar}) + (send _ $%RETURN_NEW_ARRAY_WHEN_ARGS {int lvar ivar cvar gvar send}) (block (send _ $%ALWAYS_RETURNS_NEW_ARRAY) ...) (send _ $%RETURNS_NEW_ARRAY ...) } $%HAS_MUTATION_ALTERNATIVE ...) diff --git a/spec/rubocop/cop/performance/chain_array_allocation_spec.rb b/spec/rubocop/cop/performance/chain_array_allocation_spec.rb index d923014ca8..c2f7b1dbc3 100644 --- a/spec/rubocop/cop/performance/chain_array_allocation_spec.rb +++ b/spec/rubocop/cop/performance/chain_array_allocation_spec.rb @@ -23,6 +23,13 @@ ^^^^^ Use unchained `first` and `uniq!` (followed by `return array` if required) instead of chaining `first...uniq`. RUBY end + + it 'registers an offense for `first(do_something).uniq`' do + expect_offense(<<~RUBY) + [1, 2, 3, 4].first(do_something).uniq + ^^^^^ Use unchained `first` and `uniq!` (followed by `return array` if required) instead of chaining `first...uniq`. + RUBY + end end describe 'methods that only return an array with no block' do