Skip to content

Commit

Permalink
Fix Style/HashEachMethods with numblock
Browse files Browse the repository at this point in the history
  • Loading branch information
gsamokovarov committed Aug 12, 2022
1 parent 78532ed commit abb950d
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/rubocop/cop/style/hash_each_methods.rb
Expand Up @@ -35,13 +35,15 @@ class HashEachMethods < Base

# @!method kv_each(node)
def_node_matcher :kv_each, <<~PATTERN
(block $(send (send _ ${:keys :values}) :each) ...)
({block numblock} $(send (send _ ${:keys :values}) :each) ...)
PATTERN

def on_block(node)
register_kv_offense(node)
end

alias on_numblock on_block

private

def register_kv_offense(node)
Expand Down
13 changes: 13 additions & 0 deletions spec/rubocop/cop/style/hash_each_methods_spec.rb
Expand Up @@ -32,6 +32,19 @@
it 'does not register an offense for Hash#each_value' do
expect_no_offenses('foo.each_value { |v| p v }')
end

context 'Ruby 2.7' do
it 'registers offense, autocorrects foo#keys.each to foo#each_key with numblock' do
expect_offense(<<~RUBY)
foo.keys.each { p _1 }
^^^^^^^^^ Use `each_key` instead of `keys.each`.
RUBY

expect_correction(<<~RUBY)
foo.each_key { p _1 }
RUBY
end
end
end

context 'when receiver is a hash literal' do
Expand Down

0 comments on commit abb950d

Please sign in to comment.