diff --git a/changelog/fix_else_alignment_numblock.md b/changelog/fix_else_alignment_numblock.md new file mode 100644 index 000000000000..77bda24902ab --- /dev/null +++ b/changelog/fix_else_alignment_numblock.md @@ -0,0 +1 @@ +* [#13782](https://github.com/rubocop/rubocop/pull/13782): Fix an error `Layout/ElseAlignment` when `else` is part of a numblock. ([@earlopain][]) diff --git a/lib/rubocop/cop/layout/else_alignment.rb b/lib/rubocop/cop/layout/else_alignment.rb index a6d24bd71467..dc78cd6b7ab9 100644 --- a/lib/rubocop/cop/layout/else_alignment.rb +++ b/lib/rubocop/cop/layout/else_alignment.rb @@ -92,7 +92,7 @@ def base_range_of_rescue(node) case parent.type when :def, :defs then base_for_method_definition(parent) when :kwbegin then parent.loc.begin - when :block + when :block, :numblock assignment_node = assignment_node(parent) if same_line?(parent, assignment_node) assignment_node.source_range diff --git a/spec/rubocop/cop/layout/else_alignment_spec.rb b/spec/rubocop/cop/layout/else_alignment_spec.rb index 06d061548b8e..1b158fe83e70 100644 --- a/spec/rubocop/cop/layout/else_alignment_spec.rb +++ b/spec/rubocop/cop/layout/else_alignment_spec.rb @@ -582,6 +582,21 @@ def my_func RUBY end + it 'accepts a correctly aligned else from numblock' do + expect_no_offenses(<<~RUBY) + array_like.each do + _1 + puts 'do something error prone' + rescue SomeException + puts 'error handling' + rescue + puts 'error handling' + else + puts 'normal handling' + end + RUBY + end + it 'accepts a correctly aligned else with assignment' do expect_no_offenses(<<~RUBY) result = array_like.each do |n|