Sha256: 2b5aac6d66df8b048cb1f2380d7366a5daa9502ea7378731a26e0f8b2216812a

Contents?: true

Size: 1.21 KB

Versions: 29

Compression:

Stored size: 1.21 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 < Base
        extend AutoCorrector

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

        def_node_matcher :multiple_compare?, <<~PATTERN
          (send (send _ {:< :> :<= :>=} $_) {:#{COMPARISON_METHODS.join(' :')}} _)
        PATTERN

        def on_send(node)
          return unless (center = multiple_compare?(node))

          add_offense(node) do |corrector|
            new_center = "#{center.source} && #{center.source}"

            corrector.replace(center, new_center)
          end
        end
      end
    end
  end
end

Version data entries

29 entries across 29 versions & 2 rubygems

Version Path
plaid-14.13.0 vendor/bundle/ruby/3.0.0/gems/rubocop-0.91.1/lib/rubocop/cop/lint/multiple_comparison.rb
plaid-14.12.1 vendor/bundle/ruby/3.0.0/gems/rubocop-0.91.1/lib/rubocop/cop/lint/multiple_comparison.rb
plaid-14.12.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/lint/multiple_comparison.rb
plaid-14.11.1 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/lint/multiple_comparison.rb
plaid-14.10.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/lint/multiple_comparison.rb
plaid-14.7.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/lint/multiple_comparison.rb
rubocop-1.9.1 lib/rubocop/cop/lint/multiple_comparison.rb
rubocop-1.9.0 lib/rubocop/cop/lint/multiple_comparison.rb
rubocop-1.8.1 lib/rubocop/cop/lint/multiple_comparison.rb
rubocop-1.8.0 lib/rubocop/cop/lint/multiple_comparison.rb
rubocop-1.7.0 lib/rubocop/cop/lint/multiple_comparison.rb
rubocop-1.6.1 lib/rubocop/cop/lint/multiple_comparison.rb
rubocop-1.6.0 lib/rubocop/cop/lint/multiple_comparison.rb
rubocop-1.5.2 lib/rubocop/cop/lint/multiple_comparison.rb
rubocop-1.5.1 lib/rubocop/cop/lint/multiple_comparison.rb
rubocop-1.5.0 lib/rubocop/cop/lint/multiple_comparison.rb
rubocop-1.4.2 lib/rubocop/cop/lint/multiple_comparison.rb
rubocop-1.4.1 lib/rubocop/cop/lint/multiple_comparison.rb
rubocop-1.4.0 lib/rubocop/cop/lint/multiple_comparison.rb
rubocop-1.3.1 lib/rubocop/cop/lint/multiple_comparison.rb