diff --git a/changelog/fix_an_error_for_style_multiline_ternary_operator.md b/changelog/fix_an_error_for_style_multiline_ternary_operator.md new file mode 100644 index 00000000000..92f86f3d7cb --- /dev/null +++ b/changelog/fix_an_error_for_style_multiline_ternary_operator.md @@ -0,0 +1 @@ +* [#10711](https://github.com/rubocop/rubocop/issues/10711): Fix an error for `Style/MultilineTernaryOperator` when the false branch is on a separate line. ([@koic][]) diff --git a/lib/rubocop/cop/style/multiline_ternary_operator.rb b/lib/rubocop/cop/style/multiline_ternary_operator.rb index bfeb1cf8de0..fe769960812 100644 --- a/lib/rubocop/cop/style/multiline_ternary_operator.rb +++ b/lib/rubocop/cop/style/multiline_ternary_operator.rb @@ -73,7 +73,7 @@ def replacement(node) end def enforce_single_line_ternary_operator?(node) - SINGLE_LINE_TYPES.include?(node.parent.type) && !use_assignment_method?(node.parent) + SINGLE_LINE_TYPES.include?(node.parent&.type) && !use_assignment_method?(node.parent) end def use_assignment_method?(node) diff --git a/spec/rubocop/cop/style/multiline_ternary_operator_spec.rb b/spec/rubocop/cop/style/multiline_ternary_operator_spec.rb index 29059b00c0c..1e48855b034 100644 --- a/spec/rubocop/cop/style/multiline_ternary_operator_spec.rb +++ b/spec/rubocop/cop/style/multiline_ternary_operator_spec.rb @@ -18,7 +18,7 @@ RUBY end - it 'registers an offense and corrects when the false branch is on a separate line' do + it 'registers an offense and corrects when the false branch is on a separate line and assigning a return value' do expect_offense(<<~RUBY) a = cond ? b : ^^^^^^^^^^ Avoid multi-line ternary operators, use `if` or `unless` instead. @@ -34,6 +34,22 @@ RUBY end + it 'registers an offense and corrects when the false branch is on a separate line' do + expect_offense(<<~RUBY) + cond ? b : + ^^^^^^^^^^ Avoid multi-line ternary operators, use `if` or `unless` instead. + c + RUBY + + expect_correction(<<~RUBY) + if cond + b + else + c + end + RUBY + end + it 'registers an offense and corrects when everything is on a separate line' do expect_offense(<<~RUBY) a = cond ?