Skip to content

Commit

Permalink
[Fix rubocop#7831] Fix a false positive for Style/HashEachMethods
Browse files Browse the repository at this point in the history
Fixes rubocop#7831.

This PR fix a false positive for `Style/HashEachMethods` when there is no
receiver for `keys` and `values`.

The following is an examples.

```ruby
values.each { |k, v| do_something(k, v) }
keys.each { |k, v| do_something(k, v) }
```

False negatives occur in cases such as object that inherit Hash,
but that is perhaps a corner case.
I think it is more worthwhile to resolve the false positives with
common naming of `values`.
  • Loading branch information
koic committed Mar 31, 2020
1 parent 40b8771 commit 3d63c6d
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 14 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -35,6 +35,7 @@
* [#7814](https://github.com/rubocop-hq/rubocop/issues/7814): Fix a false positive for `Migrate/DepartmentName` cop when inspecting an unexpected disabled comment format. ([@koic][])
* [#7728](https://github.com/rubocop-hq/rubocop/issues/7728): Fix an error for `Style/OneLineConditional` when one of the branches contains a self keyword. ([@koic][])
* [#7825](https://github.com/rubocop-hq/rubocop/issues/7825): Fix crash for `Layout/MultilineMethodCallIndentation` with key access to hash. ([@tejasbubane][])
* [#7831](https://github.com/rubocop-hq/rubocop/issues/7831): Fix a false positive for `Style/HashEachMethods` when receiver is implicit. ([@koic][])

### Changes

Expand Down
2 changes: 2 additions & 0 deletions lib/rubocop/cop/style/hash_each_methods.rb
Expand Up @@ -40,6 +40,8 @@ def autocorrect(node)

def register_kv_offense(node)
kv_each(node) do |target, method|
return unless target.receiver.receiver

msg = format(message, prefer: "each_#{method[0..-2]}",
current: "#{method}.each")

Expand Down
18 changes: 4 additions & 14 deletions spec/rubocop/cop/style/hash_each_methods_spec.rb
Expand Up @@ -69,25 +69,15 @@
end

context 'when receiver is implicit' do
it 'registers an offense and auto-corrects keys.each with each_key' do
expect_offense(<<~RUBY)
it 'does not register an offense for `keys.each`' do
expect_no_offenses(<<~RUBY)
keys.each { |k| p k }
^^^^^^^^^ Use `each_key` instead of `keys.each`.
RUBY

expect_correction(<<~RUBY)
each_key { |k| p k }
RUBY
end

it 'registers an offense and auto-corrects values.each with each_value' do
expect_offense(<<~RUBY)
it 'does not register an offense for `values.each`' do
expect_no_offenses(<<~RUBY)
values.each { |v| p v }
^^^^^^^^^^^ Use `each_value` instead of `values.each`.
RUBY

expect_correction(<<~RUBY)
each_value { |v| p v }
RUBY
end

Expand Down

0 comments on commit 3d63c6d

Please sign in to comment.