diff --git a/changelog/fix_an_incorrect_autocorrect_for_style_redundant_conditional.md b/changelog/fix_an_incorrect_autocorrect_for_style_redundant_conditional.md new file mode 100644 index 00000000000..82c60442860 --- /dev/null +++ b/changelog/fix_an_incorrect_autocorrect_for_style_redundant_conditional.md @@ -0,0 +1 @@ +* [#12202](https://github.com/rubocop/rubocop/pull/12202): Fix an incorrect autocorrect for `Style/RedundantConditional` when unless/else with boolean results. ([@ydah][]) diff --git a/lib/rubocop/cop/style/redundant_conditional.rb b/lib/rubocop/cop/style/redundant_conditional.rb index 30cdd053b5b..f98b33af695 100644 --- a/lib/rubocop/cop/style/redundant_conditional.rb +++ b/lib/rubocop/cop/style/redundant_conditional.rb @@ -70,19 +70,11 @@ def offense?(node) def replacement_condition(node) condition = node.condition.source - expression = invert_expression?(node) ? "!(#{condition})" : condition + expression = redundant_condition_inverted?(node) ? "!(#{condition})" : condition node.elsif? ? indented_else_node(expression, node) : expression end - def invert_expression?(node) - ( - (node.if? || node.elsif? || node.ternary?) && redundant_condition_inverted?(node) - ) || ( - node.unless? && redundant_condition?(node) - ) - end - def indented_else_node(expression, node) "else\n#{indentation(node)}#{expression}" end diff --git a/spec/rubocop/cop/style/redundant_conditional_spec.rb b/spec/rubocop/cop/style/redundant_conditional_spec.rb index bc2c8add106..158940dbd5a 100644 --- a/spec/rubocop/cop/style/redundant_conditional_spec.rb +++ b/spec/rubocop/cop/style/redundant_conditional_spec.rb @@ -57,6 +57,36 @@ RUBY end + it 'registers an offense for unless/else with boolean results' do + expect_offense(<<~RUBY) + unless x == y + ^^^^^^^^^^^^^ This conditional expression can just be replaced by `!(x == y)`. + true + else + false + end + RUBY + + expect_correction(<<~RUBY) + !(x == y) + RUBY + end + + it 'registers an offense for unless/else with negated boolean results' do + expect_offense(<<~RUBY) + unless x == y + ^^^^^^^^^^^^^ This conditional expression can just be replaced by `x == y`. + false + else + true + end + RUBY + + expect_correction(<<~RUBY) + x == y + RUBY + end + it 'registers an offense for if/elsif/else with boolean results' do expect_offense(<<~RUBY) if cond