Skip to content

Commit

Permalink
[Fix rubocop#12769] Fix a false positive for Lint/RedundantWithIndex
Browse files Browse the repository at this point in the history
Fixes rubocop#12769.

This PR fixes a false positive for `Lint/RedundantWithIndex`
when calling `with_index` with receiver and a block.
  • Loading branch information
koic committed Mar 13, 2024
1 parent afddf65 commit e7d4e31
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#12769](https://github.com/rubocop/rubocop/issues/12769): Fix a false positive for `Lint/RedundantWithIndex` when calling `with_index` with receiver and a block. ([@koic][])
3 changes: 3 additions & 0 deletions lib/rubocop/cop/lint/redundant_with_index.rb
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,10 @@ class RedundantWithIndex < Base
MSG_EACH_WITH_INDEX = 'Use `each` instead of `each_with_index`.'
MSG_WITH_INDEX = 'Remove redundant `with_index`.'

# rubocop:disable Metrics/AbcSize
def on_block(node)
return unless node.receiver
return if node.method?(:with_index) && !node.receiver.receiver
return unless (send = redundant_with_index?(node))

range = with_index_range(send)
Expand All @@ -48,6 +50,7 @@ def on_block(node)
end
end
end
# rubocop:enable Metrics/AbcSize

alias on_numblock on_block

Expand Down
4 changes: 4 additions & 0 deletions spec/rubocop/cop/lint/redundant_with_index_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,10 @@
expect_no_offenses('ary.each_with_index { _1; _2 }')
end

it 'accepts with_index with receiver and a block' do
expect_no_offenses('ary.with_index { |v| v }')
end

it 'accepts with_index without receiver with a block' do
expect_no_offenses('with_index { |v| v }')
end
Expand Down

0 comments on commit e7d4e31

Please sign in to comment.