diff --git a/changelog/fix_style_redundant_being_removing_comments_on_assignment_statement_correction.md b/changelog/fix_style_redundant_being_removing_comments_on_assignment_statement_correction.md new file mode 100644 index 00000000000..df3b266d122 --- /dev/null +++ b/changelog/fix_style_redundant_being_removing_comments_on_assignment_statement_correction.md @@ -0,0 +1 @@ +* [#9639](https://github.com/rubocop/rubocop/pull/9639): Fix `Style/RedundantBegin` removing comments on assignment statement correction. ([@marcotc][]) diff --git a/lib/rubocop/cop/style/redundant_begin.rb b/lib/rubocop/cop/style/redundant_begin.rb index 6ccf4b3dc09..1af81634648 100644 --- a/lib/rubocop/cop/style/redundant_begin.rb +++ b/lib/rubocop/cop/style/redundant_begin.rb @@ -114,6 +114,17 @@ def replace_begin_with_statement(corrector, offense_range, node) corrector.replace(offense_range, first_child.source) corrector.remove(range_between(offense_range.end_pos, first_child.source_range.end_pos)) + + restore_removed_comments(corrector, offense_range, node, first_child) + end + + # Restore comments that occur between "begin" and "first_child". + # These comments will be moved to above the assignment line. + def restore_removed_comments(corrector, offense_range, node, first_child) + comments_range = range_between(offense_range.end_pos, first_child.source_range.begin_pos) + comments = comments_range.source + + corrector.insert_before(node.parent, comments) unless comments.blank? end def empty_begin?(node) diff --git a/spec/rubocop/cop/style/redundant_begin_spec.rb b/spec/rubocop/cop/style/redundant_begin_spec.rb index dde33561915..f85db46c076 100644 --- a/spec/rubocop/cop/style/redundant_begin_spec.rb +++ b/spec/rubocop/cop/style/redundant_begin_spec.rb @@ -197,14 +197,21 @@ def method it 'registers and corrects an offense when using `begin` with single statement for or assignment' do expect_offense(<<~RUBY) - var ||= begin + # outer comment + var ||= begin # inner comment 1 ^^^^^ Redundant `begin` block detected. + # inner comment 2 foo + # inner comment 3 end RUBY expect_correction(<<~RUBY) - var ||= foo + # outer comment + # inner comment 1 + # inner comment 2 + var ||= foo + # inner comment 3 RUBY end