forked from rubocop/rubocop
/
multiple_comparison.rb
48 lines (42 loc) · 1.15 KB
/
multiple_comparison.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# frozen_string_literal: true
module RuboCop
module Cop
module Lint
# In math and Python, we can use `x < y < z` style comparison to compare
# multiple value. However, we can't use the comparison in Ruby. However,
# the comparison is not syntax error. This cop checks the bad usage of
# comparison operators.
#
# @example
#
# # bad
#
# x < y < z
# 10 <= x <= 20
#
# @example
#
# # good
#
# x < y && y < z
# 10 <= x && x <= 20
class MultipleComparison < Cop
MSG = 'Use the `&&` operator to compare multiple values.'
def_node_matcher :multiple_compare?, <<~PATTERN
(send (send _ {:< :> :<= :>=} $_) {:< :> :<= :>=} _)
PATTERN
def on_send(node)
return unless multiple_compare?(node)
add_offense(node)
end
def autocorrect(node)
center = multiple_compare?(node)
new_center = "#{center.source} && #{center.source}"
lambda do |corrector|
corrector.replace(center, new_center)
end
end
end
end
end
end