Skip to content

Commit

Permalink
[Fix rubocop#13202] Fix an incorrect autocorrect for `Style/Combinabl…
Browse files Browse the repository at this point in the history
…eLoops`

Fixes rubocop#13202.

This PR fixes an incorrect autocorrect for `Style/CombinableLoops`
when looping over the same data with different block variable names.
  • Loading branch information
koic committed Sep 6, 2024
1 parent a50857f commit c7c98c1
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#13202](https://github.com/rubocop/rubocop/issues/13202): Fix an incorrect autocorrect for `Style/CombinableLoops` when looping over the same data with different block variable names. ([@koic][])
7 changes: 7 additions & 0 deletions lib/rubocop/cop/style/combinable_loops.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ module Style
# can be combined into a single loop. It is very likely that combining them
# will make the code more efficient and more concise.
#
# NOTE: Autocorrection is not applied when the block variable names differ in separate loops,
# as it is impossible to determine which variable name should be prioritized.
#
# @safety
# The cop is unsafe, because the first loop might modify state that the
# second loop depends on; these two aren't combinable.
Expand Down Expand Up @@ -61,16 +64,20 @@ class CombinableLoops < Base

MSG = 'Combine this loop with the previous loop.'

# rubocop:disable Metrics/CyclomaticComplexity
def on_block(node)
return unless node.parent&.begin_type?
return unless collection_looping_method?(node)
return unless same_collection_looping_block?(node, node.left_sibling)
return unless node.body && node.left_sibling.body

add_offense(node) do |corrector|
next unless node.arguments == node.left_sibling.arguments

combine_with_left_sibling(corrector, node)
end
end
# rubocop:enable Metrics/CyclomaticComplexity

alias on_numblock on_block

Expand Down
10 changes: 10 additions & 0 deletions spec/rubocop/cop/style/combinable_loops_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,16 @@
RUBY
end

it 'registers an offense and does not correct when looping over the same data with different block variable names' do
expect_offense(<<~RUBY)
items.each { |item| foo(item) }
items.each { |x| bar(x) }
^^^^^^^^^^^^^^^^^^^^^^^^^ Combine this loop with the previous loop.
RUBY

expect_no_corrections
end

it 'registers an offense when looping over the same data for the third consecutive time with numbered blocks' do
expect_offense(<<~RUBY)
items.each { foo(_1) }
Expand Down

0 comments on commit c7c98c1

Please sign in to comment.