From 28e11ec805bd40db233636ca14151da47d982c29 Mon Sep 17 00:00:00 2001 From: Tejas Bubane Date: Tue, 20 Apr 2021 00:07:27 +0530 Subject: [PATCH] [Fix #9713] Fix autocorrection for block local variables in `Lint/UnusedBlockArgument` Closes #9713 --- .../fix_autocorrect_for_lint_unused_block_argument.md | 1 + lib/rubocop/cop/lint/unused_block_argument.rb | 8 +++++++- spec/rubocop/cop/lint/unused_block_argument_spec.rb | 11 +++++++++++ 3 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 changelog/fix_autocorrect_for_lint_unused_block_argument.md diff --git a/changelog/fix_autocorrect_for_lint_unused_block_argument.md b/changelog/fix_autocorrect_for_lint_unused_block_argument.md new file mode 100644 index 00000000000..c2024fcc236 --- /dev/null +++ b/changelog/fix_autocorrect_for_lint_unused_block_argument.md @@ -0,0 +1 @@ +* [#9713](https://github.com/rubocop/rubocop/issues/9713): Fix autocorrection for block local variables in `Lint/UnusedBlockArgument`. ([@tejasbubane][]) diff --git a/lib/rubocop/cop/lint/unused_block_argument.rb b/lib/rubocop/cop/lint/unused_block_argument.rb index b32fb2d5a88..7ee7b59b2bc 100644 --- a/lib/rubocop/cop/lint/unused_block_argument.rb +++ b/lib/rubocop/cop/lint/unused_block_argument.rb @@ -67,11 +67,17 @@ def autocorrect(corrector, node) end def check_argument(variable) - return if allowed_block?(variable) || allowed_keyword_argument?(variable) + return if allowed_block?(variable) || + allowed_keyword_argument?(variable) || + used_block_local?(variable) super end + def used_block_local?(variable) + variable.explicit_block_local_variable? && !variable.assignments.empty? + end + def allowed_block?(variable) !variable.block_argument? || (ignore_empty_blocks? && empty_block?(variable)) end diff --git a/spec/rubocop/cop/lint/unused_block_argument_spec.rb b/spec/rubocop/cop/lint/unused_block_argument_spec.rb index e3a5ff558f7..e584b7ad09d 100644 --- a/spec/rubocop/cop/lint/unused_block_argument_spec.rb +++ b/spec/rubocop/cop/lint/unused_block_argument_spec.rb @@ -214,6 +214,17 @@ RUBY end end + + context 'and the variable is used' do + it 'does not register offense' do + expect_no_offenses(<<~RUBY) + 1.times do |index; x| + x = 10 + puts index + end + RUBY + end + end end context 'when a lambda block takes arguments' do