Skip to content

Commit

Permalink
[Fix #9349] Fix a false positive for Lint/MultipleComparison
Browse files Browse the repository at this point in the history
Fixes #9349.

This PR fixes a false positive for `Lint/MultipleComparison`
when using `&`, `|`, and `^` set operation operators in multiple comparison.
e.g. `x < y & y < z`

I think that the cop can probably allow using these operators by default.
  • Loading branch information
koic authored and bbatsov committed Feb 13, 2021
1 parent 7e89008 commit 07cd64c
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#9349](https://github.com/rubocop-hq/rubocop/issues/9349): Fix a false positive for `Lint/MultipleComparison` when using `&`, `|`, and `^` set operation operators in multiple comparison. ([@koic][])
8 changes: 4 additions & 4 deletions lib/rubocop/cop/lint/multiple_comparison.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,18 @@ module Lint
# @example
#
# # bad
#
# x < y < z
# 10 <= x <= 20
#
# @example
#
# # good
#
# x < y && y < z
# 10 <= x && x <= 20
class MultipleComparison < Base
extend AutoCorrector

MSG = 'Use the `&&` operator to compare multiple values.'
COMPARISON_METHODS = %i[< > <= >=].freeze
SET_OPERATION_OPERATORS = %i[& | ^].freeze
RESTRICT_ON_SEND = COMPARISON_METHODS

def_node_matcher :multiple_compare?, <<~PATTERN
Expand All @@ -34,6 +31,9 @@ class MultipleComparison < Base

def on_send(node)
return unless (center = multiple_compare?(node))
# It allows multiple comparison using `&`, `|`, and `^` set operation operators.
# e.g. `x >= y & y < z`
return if center.send_type? && SET_OPERATION_OPERATORS.include?(center.method_name)

add_offense(node) do |corrector|
new_center = "#{center.source} && #{center.source}"
Expand Down
12 changes: 12 additions & 0 deletions spec/rubocop/cop/lint/multiple_comparison_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,16 @@
it 'accepts to use one compare operator' do
expect_no_offenses('x < 1')
end

it 'accepts to use `&` operator' do
expect_no_offenses('x >= y & x < z')
end

it 'accepts to use `|` operator' do
expect_no_offenses('x >= y | x < z')
end

it 'accepts to use `^` operator' do
expect_no_offenses('x >= y ^ x < z')
end
end

0 comments on commit 07cd64c

Please sign in to comment.