Skip to content

Commit

Permalink
Merge pull request rubocop#12538 from koic/make_style_each_for_simple…
Browse files Browse the repository at this point in the history
…_loop_aware_of_safe_navigation_operator

[Fix rubocop#12478] Make `Style/EachForSimpleLoop` cops aware of safe navigation operator
  • Loading branch information
koic committed Dec 18, 2023
2 parents faf48f1 + bb49018 commit 5af4bad
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 3 deletions.
6 changes: 3 additions & 3 deletions lib/rubocop/cop/style/each_for_simple_loop.rb
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def offending?(node)
# @!method each_range(node)
def_node_matcher :each_range, <<~PATTERN
(block
(send
(call
(begin
(${irange erange}
(int $_) (int $_)))
Expand All @@ -64,7 +64,7 @@ def offending?(node)
# @!method each_range_with_zero_origin?(node)
def_node_matcher :each_range_with_zero_origin?, <<~PATTERN
(block
(send
(call
(begin
({irange erange}
(int 0) (int _)))
Expand All @@ -76,7 +76,7 @@ def offending?(node)
# @!method each_range_without_block_argument?(node)
def_node_matcher :each_range_without_block_argument?, <<~PATTERN
(block
(send
(call
(begin
({irange erange}
(int _) (int _)))
Expand Down
45 changes: 45 additions & 0 deletions spec/rubocop/cop/style/each_for_simple_loop_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,36 @@
end
end

context 'when using safe navigation operator' do
context 'with inline block with parameters' do
it 'autocorrects an offense' do
expect_offense(<<~RUBY)
(0...10)&.each { |n| }
^^^^^^^^^^^^^^ Use `Integer#times` for a simple loop which iterates a fixed number of times.
RUBY

expect_correction(<<~RUBY)
10.times { |n| }
RUBY
end
end

context 'with multiline block with parameters' do
it 'autocorrects an offense' do
expect_offense(<<~RUBY)
(0...10)&.each do |n|
^^^^^^^^^^^^^^ Use `Integer#times` for a simple loop which iterates a fixed number of times.
end
RUBY

expect_correction(<<~RUBY)
10.times do |n|
end
RUBY
end
end
end

it 'does not register offense for character range' do
expect_no_offenses("('a'..'b').each {}")
end
Expand Down Expand Up @@ -79,6 +109,21 @@
RUBY
end

context 'when using safe navigation operator' do
it 'autocorrects the range not starting with zero' do
expect_offense(<<~RUBY)
(3..7)&.each do
^^^^^^^^^^^^ Use `Integer#times` for a simple loop which iterates a fixed number of times.
end
RUBY

expect_correction(<<~RUBY)
5.times do
end
RUBY
end
end

it 'does not register offense for range not starting with zero and using param' do
expect_no_offenses(<<~RUBY)
(3..7).each do |n|
Expand Down

0 comments on commit 5af4bad

Please sign in to comment.