From 142e6e418af4ff4e4ab0c2de8361bbc8f0d8f967 Mon Sep 17 00:00:00 2001 From: fatkodima Date: Tue, 1 Nov 2022 23:10:50 +0200 Subject: [PATCH] Fix `Style/RedundantEach` for non-chained `each_` calls --- .../fix_style_redundant_each_for_non_chaining.md | 1 + lib/rubocop/cop/style/redundant_each.rb | 5 +++-- spec/rubocop/cop/style/redundant_each_spec.rb | 12 ++++++++++++ 3 files changed, 16 insertions(+), 2 deletions(-) create mode 100644 changelog/fix_style_redundant_each_for_non_chaining.md diff --git a/changelog/fix_style_redundant_each_for_non_chaining.md b/changelog/fix_style_redundant_each_for_non_chaining.md new file mode 100644 index 00000000000..51be089a79f --- /dev/null +++ b/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][]) diff --git a/lib/rubocop/cop/style/redundant_each.rb b/lib/rubocop/cop/style/redundant_each.rb index fa52b34ed24..c7ba6ceb5e6 100644 --- a/lib/rubocop/cop/style/redundant_each.rb +++ b/lib/rubocop/cop/style/redundant_each.rb @@ -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 diff --git a/spec/rubocop/cop/style/redundant_each_spec.rb b/spec/rubocop/cop/style/redundant_each_spec.rb index a1017dc43de..d559a85d620 100644 --- a/spec/rubocop/cop/style/redundant_each_spec.rb +++ b/spec/rubocop/cop/style/redundant_each_spec.rb @@ -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) } @@ -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