Skip to content

Commit

Permalink
Merge pull request #11142 from fatkodima/fix-style-redundant_each
Browse files Browse the repository at this point in the history
Fix `Style/RedundantEach` for non-chained `each_` calls
  • Loading branch information
koic committed Nov 3, 2022
2 parents 7007fb1 + 142e6e4 commit 0829626
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 2 deletions.
1 change: 1 addition & 0 deletions changelog/fix_style_redundant_each_for_non_chaining.md
@@ -0,0 +1 @@
* [#11142](https://github.com/rubocop/rubocop/pull/11142): Fix `Style/RedundantEach` for non-chained `each_` calls. ([@fatkodima][])
5 changes: 3 additions & 2 deletions lib/rubocop/cop/style/redundant_each.rb
Expand Up @@ -61,9 +61,10 @@ def on_send(node)

# rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def redundant_each_method(node)
if node.method?(:each) && !node.parent.block_type?
if node.method?(:each) && !node.parent&.block_type?
ancestor_node = node.each_ancestor(:send).detect do |ancestor|
RESTRICT_ON_SEND.include?(ancestor.method_name) || ancestor.method?(:reverse_each)
ancestor.receiver == node &&
(RESTRICT_ON_SEND.include?(ancestor.method_name) || ancestor.method?(:reverse_each))
end
end

Expand Down
12 changes: 12 additions & 0 deletions spec/rubocop/cop/style/redundant_each_spec.rb
Expand Up @@ -114,6 +114,12 @@
RUBY
end

it 'does not register an offense when using `each` as enumerator' do
expect_no_offenses(<<~RUBY)
array.each
RUBY
end

it 'does not register an offense when using `each.with_index`' do
expect_no_offenses(<<~RUBY)
array.each.with_index { |v, i| do_something(v, i) }
Expand Down Expand Up @@ -181,4 +187,10 @@
array.each_foo { |i| foo(i) }.each_with_object([]) { |i| bar(i) }
RUBY
end

it 'does not register an offense when not chaining `each_` calls' do
expect_no_offenses(<<~RUBY)
[foo.each].each
RUBY
end
end

0 comments on commit 0829626

Please sign in to comment.