diff --git a/CHANGELOG.md b/CHANGELOG.md index ce1ae64b04b..1a72ed8fc2a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ * [#8726](https://github.com/rubocop-hq/rubocop/issues/8726): Fix a false positive for `Naming/VariableNumber` when naming multibyte character variable name. ([@koic][]) * [#8730](https://github.com/rubocop-hq/rubocop/issues/8730): Fix an error for `Lint/UselessTimes` when there is a blank line in the method definition. ([@koic][]) * [#8740](https://github.com/rubocop-hq/rubocop/issues/8740): Fix a false positive for `Style/HashAsLastArrayItem` when the hash is in an implicit array. ([@dvandersluis][]) +* [#8739](https://github.com/rubocop-hq/rubocop/issues/8739): Fix an error for `Lint/UselessTimes` when using empty block argument. ([@koic][]) ### Changes diff --git a/lib/rubocop/cop/lint/useless_times.rb b/lib/rubocop/cop/lint/useless_times.rb index 32c4703c172..9c7ef6e609e 100644 --- a/lib/rubocop/cop/lint/useless_times.rb +++ b/lib/rubocop/cop/lint/useless_times.rb @@ -49,7 +49,7 @@ def on_send(node) add_offense(node, message: format(MSG, count: count)) do |corrector| next unless own_line?(node) - if count < 1 + if never_process?(count, node) remove_node(corrector, node) elsif !proc_name.empty? autocorrect_block_pass(corrector, node, proc_name) @@ -61,6 +61,10 @@ def on_send(node) private + def never_process?(count, node) + count < 1 || node.block_type? && node.body.nil? + end + def remove_node(corrector, node) corrector.remove(range_by_whole_lines(node.loc.expression, include_final_newline: true)) end diff --git a/spec/rubocop/cop/lint/useless_times_spec.rb b/spec/rubocop/cop/lint/useless_times_spec.rb index b609dcba3eb..1e1574d97b4 100644 --- a/spec/rubocop/cop/lint/useless_times_spec.rb +++ b/spec/rubocop/cop/lint/useless_times_spec.rb @@ -61,6 +61,21 @@ RUBY end + it 'registers an offense and corrects when 1.times with empty block argument' do + expect_offense(<<~RUBY) + def foo + 1.times do + ^^^^^^^^^^ Useless call to `1.times` detected. + end + end + RUBY + + expect_correction(<<~RUBY) + def foo + end + RUBY + end + it 'registers an offense and corrects when there is a blank line in the method definition' do expect_offense(<<~RUBY) def foo