Skip to content

Commit

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

This PR fixes a false positive for `Style/HashExcept`
when comparing with hash value.
  • Loading branch information
koic committed Aug 24, 2021
1 parent f145884 commit da9b99e
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 3 deletions.
1 change: 1 addition & 0 deletions changelog/fix_false_positive_for_style_hash_except.md
@@ -0,0 +1 @@
* [#10031](https://github.com/rubocop/rubocop/issues/10031): Fix a false positive for `Style/HashExcept` when comparing with hash value. ([@koic][])
7 changes: 4 additions & 3 deletions lib/rubocop/cop/style/hash_except.rb
Expand Up @@ -49,7 +49,7 @@ def on_send(node)
return unless bad_method?(block) && semantically_except_method?(node, block)

except_key = except_key(block)
return unless safe_to_register_offense?(block, except_key)
return if except_key.nil? || !safe_to_register_offense?(block, except_key)

range = offense_range(node)
preferred_method = "except(#{except_key.source})"
Expand Down Expand Up @@ -81,10 +81,11 @@ def safe_to_register_offense?(block, except_key)
end

def except_key(node)
key_argument = node.argument_list.first
key_argument = node.argument_list.first.source
lhs, _method_name, rhs = *node.body
return if [lhs, rhs].map(&:source).none?(key_argument)

[lhs, rhs].find { |operand| operand.source != key_argument.source }
[lhs, rhs].find { |operand| operand.source != key_argument }
end

def offense_range(node)
Expand Down
6 changes: 6 additions & 0 deletions spec/rubocop/cop/style/hash_except_spec.rb
Expand Up @@ -96,6 +96,12 @@
{foo: 1, bar: 2, baz: 3}.keep_if { |k, v| k != :bar }
RUBY
end

it 'does not register an offense when comparing with hash value' do
expect_no_offenses(<<~RUBY)
{foo: 1, bar: 2, baz: 3}.reject { |k, v| v.eql? :bar }
RUBY
end
end

context 'Ruby 2.7 or lower', :ruby27 do
Expand Down

0 comments on commit da9b99e

Please sign in to comment.