diff --git a/changelog/fix_an_incorrect_autocorrect_for_style_map_compact_with_conditional_block.md b/changelog/fix_an_incorrect_autocorrect_for_style_map_compact_with_conditional_block.md new file mode 100644 index 000000000000..95221870820d --- /dev/null +++ b/changelog/fix_an_incorrect_autocorrect_for_style_map_compact_with_conditional_block.md @@ -0,0 +1 @@ +* [#12683](https://github.com/rubocop/rubocop/issues/12683): Fix an incorrect autocorrect for `Style/MapCompactWithConditionalBlock` when using guard clause with `next` implicitly nil. ([@koic][]) diff --git a/lib/rubocop/cop/style/map_compact_with_conditional_block.rb b/lib/rubocop/cop/style/map_compact_with_conditional_block.rb index 24b85f91e521..d880fbca7731 100644 --- a/lib/rubocop/cop/style/map_compact_with_conditional_block.rb +++ b/lib/rubocop/cop/style/map_compact_with_conditional_block.rb @@ -116,10 +116,10 @@ def truthy_branch_for_if?(node) def truthy_branch_for_guard?(node) if_node = node.left_sibling - if if_node.if? || if_node.ternary? - if_node.else_branch.nil? - elsif if_node.unless? - if_node.if_branch.nil? + if if_node.if? + if_node.if_branch.arguments.any? + else + if_node.if_branch.arguments.none? end end diff --git a/spec/rubocop/cop/style/map_compact_with_conditional_block_spec.rb b/spec/rubocop/cop/style/map_compact_with_conditional_block_spec.rb index 0ce0b54c283e..76404fa6fb47 100644 --- a/spec/rubocop/cop/style/map_compact_with_conditional_block_spec.rb +++ b/spec/rubocop/cop/style/map_compact_with_conditional_block_spec.rb @@ -158,10 +158,10 @@ RUBY end - it 'registers an offense and corrects to `select` with guard clause of `if`' do + it 'registers an offense and corrects to `reject` with guard clause of `if`' do expect_offense(<<~RUBY) foo.map do |item| - ^^^^^^^^^^^^^ Replace `map { ... }.compact` with `select`. + ^^^^^^^^^^^^^ Replace `map { ... }.compact` with `reject`. next if item.bar? item @@ -169,14 +169,14 @@ RUBY expect_correction <<~RUBY - foo.select { |item| item.bar? } + foo.reject { |item| item.bar? } RUBY end - it 'registers an offense and corrects to `reject` with guard clause of `unless`' do + it 'registers an offense and corrects to `select` with guard clause of `unless`' do expect_offense(<<~RUBY) foo.map do |item| - ^^^^^^^^^^^^^ Replace `map { ... }.compact` with `reject`. + ^^^^^^^^^^^^^ Replace `map { ... }.compact` with `select`. next unless item.bar? item @@ -184,7 +184,7 @@ RUBY expect_correction <<~RUBY - foo.reject { |item| item.bar? } + foo.select { |item| item.bar? } RUBY end