Sha256: 75738df6d6c61f591b8c6ffb0fe1c68f2914d36c24734151995234a6b0bbb575

Contents?: true

Size: 1.18 KB

Versions: 4

Compression:

Stored size: 1.18 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 MultipleCompare < Cop
        MSG = 'Use the `&&` operator to compare multiple values.'.freeze

        def_node_matcher :multiple_compare?, <<-PATTERN
          (send (send _ {:< :> :<= :>=} $_) {:< :> :<= :>=} _)
        PATTERN

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

          add_offense(node, :expression)
        end

        def autocorrect(node)
          center = multiple_compare?(node)
          new_center = "#{center.source} && #{center.source}"

          lambda do |corrector|
            corrector.replace(center.source_range, new_center)
          end
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
rubocop-0.49.1 lib/rubocop/cop/lint/multiple_compare.rb
rubocop-0.49.0 lib/rubocop/cop/lint/multiple_compare.rb
rubocop-0.48.1 lib/rubocop/cop/lint/multiple_compare.rb
rubocop-0.48.0 lib/rubocop/cop/lint/multiple_compare.rb