Skip to content

Commit

Permalink
[Fix rubocop#12322] Fix an error for Style/CombinableLoops
Browse files Browse the repository at this point in the history
Fixes rubocop#12322.

This PR fixes an error for `Style/CombinableLoops`
when looping over the same data for the third consecutive time or more.
  • Loading branch information
koic committed Nov 1, 2023
1 parent f981a1a commit 558a739
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 7 deletions.
1 change: 1 addition & 0 deletions changelog/fix_error_for_style_combinable_loops.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#12322](https://github.com/rubocop/rubocop/issues/12322): Fix an error for `Style/CombinableLoops` when looping over the same data for the third consecutive time or more. ([@koic][])
9 changes: 2 additions & 7 deletions lib/rubocop/cop/style/combinable_loops.rb
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,6 @@ module Style
class CombinableLoops < Base
extend AutoCorrector

include RangeHelp

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

def on_block(node)
Expand Down Expand Up @@ -105,11 +103,8 @@ def same_collection_looping_for?(node, sibling)
end

def combine_with_left_sibling(corrector, node)
corrector.replace(
node.left_sibling.body,
"#{node.left_sibling.body.source}\n#{node.body.source}"
)
corrector.remove(range_with_surrounding_space(range: node.source_range, side: :left))
corrector.remove(node.left_sibling.body.source_range.end.join(node.left_sibling.loc.end))
corrector.remove(node.source_range.begin.join(node.body.source_range.begin))
end
end
end
Expand Down
16 changes: 16 additions & 0 deletions spec/rubocop/cop/style/combinable_loops_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,22 @@
RUBY
end

it 'registers an offense when looping over the same data for the third consecutive time' do
expect_offense(<<~RUBY)
items.each { |item| foo(item) }
items.each { |item| bar(item) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Combine this loop with the previous loop.
items.each { |item| baz(item) }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Combine this loop with the previous loop.
RUBY

expect_correction(<<~RUBY)
items.each { |item| foo(item)
bar(item)
baz(item) }
RUBY
end

context 'Ruby 2.7' do
it 'registers an offense when looping over the same data as previous loop in numblocks' do
expect_offense(<<~RUBY)
Expand Down

0 comments on commit 558a739

Please sign in to comment.