Skip to content

Commit

Permalink
[Fix #11137] Fix a false positive for Style/RedundantEach when usin…
Browse files Browse the repository at this point in the history
…g `each` with a symbol proc argument

Fix: #11137
  • Loading branch information
ydah committed Nov 3, 2022
1 parent ab51fa2 commit 2dbfbd2
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#11137](https://github.com/rubocop/rubocop/issues/11137): Fix a false positive for `Style/RedundantEach` when using a symbol proc argument. ([@ydah][])
4 changes: 3 additions & 1 deletion lib/rubocop/cop/style/redundant_each.rb
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ def on_send(node)

# rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def redundant_each_method(node)
return if node.last_argument&.block_pass_type?

if node.method?(:each) && !node.parent&.block_type?
ancestor_node = node.each_ancestor(:send).detect do |ancestor|
ancestor.receiver == node &&
Expand All @@ -69,7 +71,7 @@ def redundant_each_method(node)
end

ancestor_node || node.each_descendant(:send).detect do |descendant|
next if descendant.parent.block_type?
next if descendant.parent.block_type? || descendant.last_argument&.block_pass_type?

detected = descendant.method_name.to_s.start_with?('each_') unless node.method?(:each)

Expand Down
31 changes: 31 additions & 0 deletions spec/rubocop/cop/style/redundant_each_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,17 @@
RUBY
end

it 'registers an offense when using `each.each(&:foo)`' do
expect_offense(<<~RUBY)
array.each.each(&:foo)
^^^^^ Remove redundant `each`.
RUBY

expect_correction(<<~RUBY)
array.each(&:foo)
RUBY
end

it 'registers an offense when using `each.each_with_index`' do
expect_offense(<<~RUBY)
array.each.each_with_index { |v| do_something(v) }
Expand Down Expand Up @@ -193,4 +204,24 @@
[foo.each].each
RUBY
end

it 'does not register an offense when using `each` with a symbol proc argument' do
expect_no_offenses(<<~RUBY)
array.each(&:foo).each do |i|
end
RUBY
end

it 'does not register an offense when using `each` with a symbol proc for last argument' do
expect_no_offenses(<<~RUBY)
array.each(foo, &:bar).each do |i|
end
RUBY
end

it 'does not register an offense when using `reverse_each(&:foo).each {...}`' do
expect_no_offenses(<<~RUBY)
array.reverse_each(&:foo).each { |i| bar(i) }
RUBY
end
end

0 comments on commit 2dbfbd2

Please sign in to comment.