diff --git a/changelog/fix_a_false_positive_for_style_hash_except.md b/changelog/fix_a_false_positive_for_style_hash_except.md new file mode 100644 index 00000000000..0ab18bd892a --- /dev/null +++ b/changelog/fix_a_false_positive_for_style_hash_except.md @@ -0,0 +1 @@ +* [#10843](https://github.com/rubocop/rubocop/issues/10843): Fix a false positive for `Style/HashExcept` when using `reject` and calling `include?` method with symbol array and second block value. ([@koic][]) diff --git a/lib/rubocop/cop/style/hash_except.rb b/lib/rubocop/cop/style/hash_except.rb index 4bad19d08e6..b00d8eb602f 100644 --- a/lib/rubocop/cop/style/hash_except.rb +++ b/lib/rubocop/cop/style/hash_except.rb @@ -159,10 +159,6 @@ def except_key(node) key_argument = node.argument_list.first.source body = extract_body_if_nagated(node.body) lhs, _method_name, rhs = *body - - return lhs if body.method?('include?') - return lhs if body.method?('exclude?') - return rhs if body.method?('in?') return if [lhs, rhs].map(&:source).none?(key_argument) [lhs, rhs].find { |operand| operand.source != key_argument } diff --git a/spec/rubocop/cop/style/hash_except_spec.rb b/spec/rubocop/cop/style/hash_except_spec.rb index 265e87a2bcf..328512c5d06 100644 --- a/spec/rubocop/cop/style/hash_except_spec.rb +++ b/spec/rubocop/cop/style/hash_except_spec.rb @@ -166,6 +166,12 @@ {foo: 1, bar: 2, baz: 3}.except(*array) RUBY end + + it 'does not register an offense when using `reject` and calling `include?` method with symbol array and second block value' do + expect_no_offenses(<<~RUBY) + {foo: 1, bar: 2, baz: 3}.reject { |k, v| ![1, 2].include?(v) } + RUBY + end end context 'using `exclude?`' do @@ -364,6 +370,12 @@ {foo: 1, bar: 2, baz: 3}.except(*array) RUBY end + + it 'does not register an offense when using `reject` and calling `in?` method with symbol array and second block value' do + expect_no_offenses(<<~RUBY) + {foo: 1, bar: 2, baz: 3}.reject { |k, v| v.in?([1, 2]) } + RUBY + end end context 'using `include?`' do @@ -526,6 +538,12 @@ {foo: 1, bar: 2, baz: 3}.except(*array) RUBY end + + it 'does not register an offense when using `reject` and calling `exclude?` method with symbol array and second block value' do + expect_no_offenses(<<~RUBY) + {foo: 1, bar: 2, baz: 3}.reject { |k, v| ![1, 2].exclude?(v) } + RUBY + end end it 'does not register an offense when using `reject` and other than comparison by string and symbol using `==`' do