diff --git a/changelog/fix_block_delimiters_with_numbered_arguments.md b/changelog/fix_block_delimiters_with_numbered_arguments.md new file mode 100644 index 00000000000..9748a000ae9 --- /dev/null +++ b/changelog/fix_block_delimiters_with_numbered_arguments.md @@ -0,0 +1 @@ +* [#10749](https://github.com/rubocop/rubocop/pull/10749): Fix Style/BlockDelimiters for blocks with numbered arguments. ([@gsamokovarov][]) diff --git a/lib/rubocop/cop/style/block_delimiters.rb b/lib/rubocop/cop/style/block_delimiters.rb index 3e517edb59b..ee8154f47ac 100644 --- a/lib/rubocop/cop/style/block_delimiters.rb +++ b/lib/rubocop/cop/style/block_delimiters.rb @@ -184,6 +184,8 @@ def on_block(node) end end + alias on_numblock on_block + private def autocorrect(corrector, node) @@ -300,7 +302,7 @@ def with_block?(node) def get_blocks(node, &block) case node.type - when :block + when :block, :numblock yield node when :send get_blocks(node.receiver, &block) if node.receiver diff --git a/spec/rubocop/cop/style/block_delimiters_spec.rb b/spec/rubocop/cop/style/block_delimiters_spec.rb index e1b216bbba8..a98ad02f4f6 100644 --- a/spec/rubocop/cop/style/block_delimiters_spec.rb +++ b/spec/rubocop/cop/style/block_delimiters_spec.rb @@ -27,6 +27,35 @@ }, 1 RUBY end + + context 'Ruby >= 2.7', :ruby27 do + it 'registers an offense for a single line numblock with do-end' do + expect_offense(<<~RUBY) + each do _1 end + ^^ Prefer `{...}` over `do...end` for single-line blocks. + RUBY + end + + it 'accepts a single line numblock with braces' do + expect_no_offenses('each { _1 }') + end + + it 'accepts a multi-line numblock with do-end' do + expect_no_offenses(<<~RUBY) + each do + _1 + end + RUBY + end + + it 'accepts a multi-line numblock that needs braces to be valid ruby' do + expect_no_offenses(<<~RUBY) + puts [1, 2, 3].map { + _1 * _1 + }, 1 + RUBY + end + end end context 'EnforcedStyle: semantic' do