diff --git a/CHANGELOG.md b/CHANGELOG.md index 86ff6b72686..8ce8c9ad717 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,7 @@ * [#8825](https://github.com/rubocop-hq/rubocop/issues/8825): Fix crash in `Style/ExplicitBlockArgument` when code is called outside of a method. ([@ghiculescu][]) * [#8718](https://github.com/rubocop-hq/rubocop/issues/8718): Fix undefined methods of pseudo location. ([@ybiquitous][]) * [#8354](https://github.com/rubocop-hq/rubocop/issues/8354): Detect regexp named captures in `Style/CaseLikeIf` cop. ([@dsavochkin][]) +* [#8821](https://github.com/rubocop-hq/rubocop/issues/8821): Fix an incorrect autocorrect for `Style/NestedTernaryOperator` when using a nested ternary operator expression with no parentheses on the outside. ([@koic][]) * [#8834](https://github.com/rubocop-hq/rubocop/issues/8834): Fix a false positive for `Style/ParenthesesAsGroupedExpression` when method argument parentheses are omitted and hash argument key is enclosed in parentheses. ([@koic][]) * [#8830](https://github.com/rubocop-hq/rubocop/issues/8830): Fix bad autocorrect of `Style/StringConcatenation` when string includes double quotes. ([@tleish][]) * [#8807](https://github.com/rubocop-hq/rubocop/pull/8807): Fix a false positive for `Style/RedundantCondition` when using assignment by hash key access. ([@koic][]) diff --git a/lib/rubocop/cop/style/nested_ternary_operator.rb b/lib/rubocop/cop/style/nested_ternary_operator.rb index 482c3273e78..6ebcb462f00 100644 --- a/lib/rubocop/cop/style/nested_ternary_operator.rb +++ b/lib/rubocop/cop/style/nested_ternary_operator.rb @@ -49,6 +49,8 @@ def if_node(node) end def remove_parentheses(source) + return source unless source.start_with?('(') + source.gsub(/\A\(/, '').gsub(/\)\z/, '') end end diff --git a/spec/rubocop/cop/style/nested_ternary_operator_spec.rb b/spec/rubocop/cop/style/nested_ternary_operator_spec.rb index 373ab9c6da1..5013f0cd544 100644 --- a/spec/rubocop/cop/style/nested_ternary_operator_spec.rb +++ b/spec/rubocop/cop/style/nested_ternary_operator_spec.rb @@ -34,6 +34,21 @@ RUBY end + it 'registers an offense and corrects for a nested ternary operator expression with no parentheses on the outside' do + expect_offense(<<~RUBY) + x ? y + (z ? 1 : 0) : nil + ^^^^^^^^^ Ternary operators must not be nested. Prefer `if` or `else` constructs instead. + RUBY + + expect_correction(<<~RUBY) + if x + y + (z ? 1 : 0) + else + nil + end + RUBY + end + it 'accepts a non-nested ternary operator within an if' do expect_no_offenses(<<~RUBY) a = if x