diff --git a/changelog/fix_fix_lintambiguousoperatorprecedence_with.md b/changelog/fix_fix_lintambiguousoperatorprecedence_with.md new file mode 100644 index 00000000000..336ed90e8a7 --- /dev/null +++ b/changelog/fix_fix_lintambiguousoperatorprecedence_with.md @@ -0,0 +1 @@ +* [#10096](https://github.com/rubocop/rubocop/issues/10096): Fix `Lint/AmbiguousOperatorPrecedence` with `and`/`or` operators. ([@dvandersluis][]) diff --git a/lib/rubocop/cop/lint/ambiguous_operator_precedence.rb b/lib/rubocop/cop/lint/ambiguous_operator_precedence.rb index 10969a5a346..9d694ae8cc5 100644 --- a/lib/rubocop/cop/lint/ambiguous_operator_precedence.rb +++ b/lib/rubocop/cop/lint/ambiguous_operator_precedence.rb @@ -87,7 +87,11 @@ def operator?(node) end def greater_precedence?(node1, node2) - precedence(node2) > precedence(node1) + node1_precedence = precedence(node1) + node2_precedence = precedence(node2) + return false unless node1_precedence && node2_precedence + + node2_precedence > node1_precedence end def operator_name(node) diff --git a/spec/rubocop/cop/lint/ambiguous_operator_precedence_spec.rb b/spec/rubocop/cop/lint/ambiguous_operator_precedence_spec.rb index 1d653212e7f..f0188d4f86f 100644 --- a/spec/rubocop/cop/lint/ambiguous_operator_precedence_spec.rb +++ b/spec/rubocop/cop/lint/ambiguous_operator_precedence_spec.rb @@ -120,4 +120,16 @@ a || (b && (c | d ^ (e & (f << g >> (h + i - (j * k / l % (n ** m))))))) RUBY end + + it 'allows an operator with `and`' do + expect_no_offenses(<<~RUBY) + array << i and next + RUBY + end + + it 'allows an operator with `or`' do + expect_no_offenses(<<~RUBY) + array << i or return + RUBY + end end