diff --git a/changelog/fix_incorrect_autocorrect_for_style_redundant_begin.md b/changelog/fix_incorrect_autocorrect_for_style_redundant_begin.md new file mode 100644 index 00000000000..0a4b4f86417 --- /dev/null +++ b/changelog/fix_incorrect_autocorrect_for_style_redundant_begin.md @@ -0,0 +1 @@ +* [#9681](https://github.com/rubocop/rubocop/issues/9681): Fix an incorrect auto-correct for `Style/RedundantBegin` when using modifier `if` single statement in `begin` block. ([@koic][]) diff --git a/lib/rubocop/cop/style/redundant_begin.rb b/lib/rubocop/cop/style/redundant_begin.rb index fabb01744a8..46f8ebd8e3c 100644 --- a/lib/rubocop/cop/style/redundant_begin.rb +++ b/lib/rubocop/cop/style/redundant_begin.rb @@ -109,7 +109,10 @@ def register_offense(node) def replace_begin_with_statement(corrector, offense_range, node) first_child = node.children.first - corrector.replace(offense_range, first_child.source) + source = first_child.source + source = "(#{source})" if first_child.if_type? + + corrector.replace(offense_range, source) corrector.remove(range_between(offense_range.end_pos, first_child.source_range.end_pos)) restore_removed_comments(corrector, offense_range, node, first_child) diff --git a/spec/rubocop/cop/style/redundant_begin_spec.rb b/spec/rubocop/cop/style/redundant_begin_spec.rb index b78beabc60d..ef0121e4cb2 100644 --- a/spec/rubocop/cop/style/redundant_begin_spec.rb +++ b/spec/rubocop/cop/style/redundant_begin_spec.rb @@ -234,6 +234,20 @@ def method RUBY end + it 'registers and corrects an offense when using modifier `if` single statement in `begin` block' do + expect_offense(<<~RUBY) + var ||= begin + ^^^^^ Redundant `begin` block detected. + foo if condition + end + RUBY + + expect_correction(<<~RUBY) + var ||= (foo if condition) + + RUBY + end + it 'does not register an offense when using `begin` with multiple statement for or assignment' do expect_no_offenses(<<~RUBY) var ||= begin