From 7b265aaff7df67fef6302dbfb803f13f1db546bf Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Sat, 12 Nov 2022 14:52:45 +0900 Subject: [PATCH] [Fix #11173] Fix an incorrect autocorrect for `Style/CollectionCompact` Fixes #11173. This PR fixes an incorrect autocorrect for `Style/CollectionCompact` when using `reject` with block pass arg and no parentheses. --- ...orrect_autocorrect_for_style_collection_compact.md | 1 + lib/rubocop/cop/style/collection_compact.rb | 2 +- spec/rubocop/cop/style/collection_compact_spec.rb | 11 +++++++++++ 3 files changed, 13 insertions(+), 1 deletion(-) create mode 100644 changelog/fix_incorrect_autocorrect_for_style_collection_compact.md diff --git a/changelog/fix_incorrect_autocorrect_for_style_collection_compact.md b/changelog/fix_incorrect_autocorrect_for_style_collection_compact.md new file mode 100644 index 00000000000..8bd02d2ebec --- /dev/null +++ b/changelog/fix_incorrect_autocorrect_for_style_collection_compact.md @@ -0,0 +1 @@ +* [#11173](https://github.com/rubocop/rubocop/issues/11173): Fix an incorrect autocorrect for `Style/CollectionCompact` when using `reject` with block pass arg and no parentheses. ([@koic][]) diff --git a/lib/rubocop/cop/style/collection_compact.rb b/lib/rubocop/cop/style/collection_compact.rb index 19afcd0052b..6ea75d6fc88 100644 --- a/lib/rubocop/cop/style/collection_compact.rb +++ b/lib/rubocop/cop/style/collection_compact.rb @@ -112,7 +112,7 @@ def good_method_name(node) end def range(begin_pos_node, end_pos_node) - range_between(begin_pos_node.loc.selector.begin_pos, end_pos_node.loc.end.end_pos) + range_between(begin_pos_node.loc.selector.begin_pos, end_pos_node.loc.expression.end_pos) end end end diff --git a/spec/rubocop/cop/style/collection_compact_spec.rb b/spec/rubocop/cop/style/collection_compact_spec.rb index 2eddc7deea7..3854cedaec1 100644 --- a/spec/rubocop/cop/style/collection_compact_spec.rb +++ b/spec/rubocop/cop/style/collection_compact_spec.rb @@ -29,6 +29,17 @@ RUBY end + it 'registers an offense and corrects when using `reject` with block pass arg and no parentheses' do + expect_offense(<<~RUBY) + array.reject &:nil? + ^^^^^^^^^^^^^ Use `compact` instead of `reject &:nil?`. + RUBY + + expect_correction(<<~RUBY) + array.compact + RUBY + end + it 'registers an offense and corrects when using `reject` on hash to reject nils' do expect_offense(<<~RUBY) hash.reject { |k, v| v.nil? }