diff --git a/CHANGELOG.md b/CHANGELOG.md index c2db9b40d8b..b3680a64bc1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ ### Bug fixes * [#8810](https://github.com/rubocop-hq/rubocop/pull/8810): Fix multiple offense detection for Style/RaiseArgs. ([@pbernays][]) +* [#8809](https://github.com/rubocop-hq/rubocop/pull/8809): Fix multiple offense detection for Style/For. ([@pbernays][]) ### Changes diff --git a/lib/rubocop/cop/style/for.rb b/lib/rubocop/cop/style/for.rb index d1ad6e0b2ea..1a53c42ced0 100644 --- a/lib/rubocop/cop/style/for.rb +++ b/lib/rubocop/cop/style/for.rb @@ -49,8 +49,6 @@ class For < Base def on_for(node) if style == :each - return unless opposite_style_detected - add_offense(node, message: PREFER_EACH) do |corrector| ForToEachCorrector.new(node).call(corrector) end @@ -63,8 +61,6 @@ def on_block(node) return unless suspect_enumerable?(node) if style == :for - return unless opposite_style_detected - add_offense(node, message: PREFER_FOR) do |corrector| EachToForCorrector.new(node).call(corrector) end diff --git a/spec/rubocop/cop/style/for_spec.rb b/spec/rubocop/cop/style/for_spec.rb index 975efcd5949..b85d08be27b 100644 --- a/spec/rubocop/cop/style/for_spec.rb +++ b/spec/rubocop/cop/style/for_spec.rb @@ -48,6 +48,34 @@ def func RUBY end + it 'registers multiple offenses' do + expect_offense(<<~RUBY) + for n in [1, 2, 3] do + ^^^^^^^^^^^^^^^^^^^^^ Prefer `each` over `for`. + puts n + end + [1, 2, 3].each do |n| + puts n + end + for n in [1, 2, 3] do + ^^^^^^^^^^^^^^^^^^^^^ Prefer `each` over `for`. + puts n + end + RUBY + + expect_correction(<<~RUBY) + [1, 2, 3].each do |n| + puts n + end + [1, 2, 3].each do |n| + puts n + end + [1, 2, 3].each do |n| + puts n + end + RUBY + end + context 'auto-correct' do context 'with range' do let(:expected_each_with_range) do @@ -249,6 +277,34 @@ def func RUBY end + it 'registers multiple offenses' do + expect_offense(<<~RUBY) + for n in [1, 2, 3] do + puts n + end + [1, 2, 3].each do |n| + ^^^^^^^^^^^^^^^^^^^^^ Prefer `for` over `each`. + puts n + end + [1, 2, 3].each do |n| + ^^^^^^^^^^^^^^^^^^^^^ Prefer `for` over `each`. + puts n + end + RUBY + + expect_correction(<<~RUBY) + for n in [1, 2, 3] do + puts n + end + for n in [1, 2, 3] do + puts n + end + for n in [1, 2, 3] do + puts n + end + RUBY + end + it 'registers an offense for a tuple of items' do expect_offense(<<~RUBY) def func