Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix a false positive for Style/HashEachMethods when both arguments are unused #12635

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#12635](https://github.com/rubocop/rubocop/pull/12635): 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