rubocop / rubocop-performance

An extension of RuboCop focused on code performance checks.
https://docs.rubocop.org/rubocop-performance
MIT License
684 stars 81 forks source link

ReturnFromInsideBlock cop to save unecessary iteration with Enumerable#any? Enumarable#none? etc. #376

Closed MatzFan closed 1 year ago

MatzFan commented 1 year ago

Feature Request

Consider this antipattern:

def foo(arr)
  return nil if arr.none? { |e| e.length > 3 }

  true
end

foo %w[egg ham foo bar] # => nil
foo %w[eggs ham foo bar] # => true, but unnecessary iteration over whole array

Solution should suggest return from inside the block or another method to avoid unnecessary iteration, e.g:

def bar(arr)
  arr.each { |e| return true if e.length > 3 } # early return possible, doesn't fall foul of Lint/NonLocalExitFromIterator
  nil
end

Describe alternatives you've considered

None

System info

rubocop -V
1.56.4 (using Parser 3.2.2.3, rubocop-ast 1.29.0, running on ruby 3.2.2) [x86_64-linux]
  - rubocop-capybara 2.18.0
  - rubocop-minitest 0.31.1
  - rubocop-performance 1.19.1
  - rubocop-rake 0.6.0
  - rubocop-sequel 0.3.4
MatzFan commented 1 year ago

Brain freeze..