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 #10031] Fix a false positive for Style/HashExcept #10032

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
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