Sha256: c0a91c1236912f219a49e9a1614051841cb49fda60d788550504dae62c6d6519

Contents?: true

Size: 1.15 KB

Versions: 14

Compression:

Stored size: 1.15 KB

Contents

# 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

Version data entries

14 entries across 14 versions & 3 rubygems

Version Path
rubocop-0.88.0 lib/rubocop/cop/lint/multiple_comparison.rb
rbhint-0.87.1.rc1 lib/rubocop/cop/lint/multiple_comparison.rb
rubocop-0.87.1 lib/rubocop/cop/lint/multiple_comparison.rb
rubocop-0.87.0 lib/rubocop/cop/lint/multiple_comparison.rb
rubocop-0.86.0 lib/rubocop/cop/lint/multiple_comparison.rb
files.com-1.0.1 vendor/bundle/ruby/2.5.0/gems/rubocop-0.85.1/lib/rubocop/cop/lint/multiple_comparison.rb
rbhint-0.85.1.rc2 lib/rubocop/cop/lint/multiple_comparison.rb
rbhint-0.85.1.rc1 lib/rubocop/cop/lint/multiple_comparison.rb
rubocop-0.85.1 lib/rubocop/cop/lint/multiple_comparison.rb
rbhint-0.8.5.rc1 lib/rubocop/cop/lint/multiple_comparison.rb
rubocop-0.85.0 lib/rubocop/cop/lint/multiple_comparison.rb
rubocop-0.84.0 lib/rubocop/cop/lint/multiple_comparison.rb
rubocop-0.83.0 lib/rubocop/cop/lint/multiple_comparison.rb
rubocop-0.82.0 lib/rubocop/cop/lint/multiple_comparison.rb