diff --git a/changelog/fix_false_positives_for_style_inverse_methods.md b/changelog/fix_false_positives_for_style_inverse_methods.md new file mode 100644 index 000000000000..78a76008b943 --- /dev/null +++ b/changelog/fix_false_positives_for_style_inverse_methods.md @@ -0,0 +1 @@ +* [#12649](https://github.com/rubocop/rubocop/issues/12649): Fix false positives for `Style/InverseMethods` when using relational comparison operator (`<`) with safe navigation operator. ([@koic][]) diff --git a/lib/rubocop/cop/style/inverse_methods.rb b/lib/rubocop/cop/style/inverse_methods.rb index c45f5df1c631..2276c9ea496a 100644 --- a/lib/rubocop/cop/style/inverse_methods.rb +++ b/lib/rubocop/cop/style/inverse_methods.rb @@ -76,9 +76,9 @@ def self.autocorrect_incompatible_with PATTERN def on_send(node) - inverse_candidate?(node) do |_method_call, lhs, method, rhs| + inverse_candidate?(node) do |method_call, lhs, method, rhs| return unless inverse_methods.key?(method) - return if negated?(node) + return if negated?(node) || relational_comparison_with_safe_navigation?(method_call) return if part_of_ignored_node?(node) return if possible_class_hierarchy_check?(lhs, rhs, method) @@ -155,6 +155,10 @@ def negated?(node) node.parent.respond_to?(:method?) && node.parent.method?(:!) end + def relational_comparison_with_safe_navigation?(node) + node.csend_type? && CLASS_COMPARISON_METHODS.include?(node.method_name) + end + def not_to_receiver(node, method_call) Parser::Source::Range.new(node.source_range.source_buffer, node.loc.selector.begin_pos, diff --git a/spec/rubocop/cop/style/inverse_methods_spec.rb b/spec/rubocop/cop/style/inverse_methods_spec.rb index b529be2e2224..d9712adfc44e 100644 --- a/spec/rubocop/cop/style/inverse_methods_spec.rb +++ b/spec/rubocop/cop/style/inverse_methods_spec.rb @@ -209,6 +209,30 @@ def test_method end end + it 'allows comparing for relational comparison operator (`<`) with safe navigation operator' do + expect_no_offenses(<<~RUBY) + !nullable&.<(0) + RUBY + end + + it 'allows comparing for relational comparison operator (`<=`) with safe navigation operator' do + expect_no_offenses(<<~RUBY) + !nullable&.<=(0) + RUBY + end + + it 'allows comparing for relational comparison operator (`>`) with safe navigation operator' do + expect_no_offenses(<<~RUBY) + !nullable&.>(0) + RUBY + end + + it 'allows comparing for relational comparison operator (`>=`) with safe navigation operator' do + expect_no_offenses(<<~RUBY) + !nullable&.>=(0) + RUBY + end + it 'allows comparing camel case constants on the right' do expect_no_offenses(<<~RUBY) klass = self.class