Skip to content

Commit

Permalink
Fix a false positive for Style/HashEachMethods when both arguments …
Browse files Browse the repository at this point in the history
…are unused.

`Lint/UnusedBlockArgument` should instead say something about this:
  • Loading branch information
Earlopain committed Jan 18, 2024
1 parent 2b27ed8 commit 755e026
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#12634](https://github.com/rubocop/rubocop/pull/12634): Fix a false positive for `Style/HashEachMethods` when both arguments are unused. ([@earlopain][])
17 changes: 12 additions & 5 deletions lib/rubocop/cop/style/hash_each_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ class HashEachMethods < Base
(call $(call _ ${:keys :values}) :each (block_pass (sym _)))
PATTERN

# rubocop:disable Metrics/AbcSize
def on_block(node)
return unless handleable?(node)

Expand All @@ -66,12 +65,22 @@ def on_block(node)

return unless (key, value = each_arguments(node))

if unused_block_arg_exist?(node, value)
check_unused_block_args(node, key, value)
end
alias on_numblock on_block

# rubocop:disable Metrics/AbcSize
def check_unused_block_args(node, key, value)
value_unused = unused_block_arg_exist?(node, value)
key_unused = unused_block_arg_exist?(node, key)
return if value_unused && key_unused

if value_unused
message = message('each_key', node.method_name, value.source)
unused_range = key.source_range.end.join(value.source_range.end)

register_each_args_offense(node, message, 'each_key', unused_range)
elsif unused_block_arg_exist?(node, key)
elsif key_unused
message = message('each_value', node.method_name, key.source)
unused_range = key.source_range.begin.join(value.source_range.begin)

Expand All @@ -80,8 +89,6 @@ def on_block(node)
end
# rubocop:enable Metrics/AbcSize

alias on_numblock on_block

def on_block_pass(node)
kv_each_with_block_pass(node.parent) do |target, method|
register_kv_with_block_pass_offense(node, target, method)
Expand Down
4 changes: 4 additions & 0 deletions spec/rubocop/cop/style/hash_each_methods_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,10 @@
expect_no_offenses('foo.each { |*k, v| do_something(*k, v) }')
end

it 'does not register an offense when both arguments of `Enumerable#each` are unused' do
expect_no_offenses('foo.each { |k, v| do_something }')
end

it 'registers an offense when the rest value block argument of `Enumerable#each` method is unused' do
expect_offense(<<~RUBY)
foo.each { |k, *v| do_something(*v) }
Expand Down

0 comments on commit 755e026

Please sign in to comment.