Sha256: 2232be1f3182d6083a4ea632d4df506e4d6a4a4d090d33559d59a00dcf7e25c1

Contents?: true

Size: 1.33 KB

Versions: 30

Compression:

Stored size: 1.33 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # This cop checks for places where `Integer#even?` or `Integer#odd?`
      # can be used.
      #
      # @example
      #
      #   # bad
      #   if x % 2 == 0
      #   end
      #
      #   # good
      #   if x.even?
      #   end
      class EvenOdd < Base
        extend AutoCorrector

        MSG = 'Replace with `Integer#%<method>s?`.'
        RESTRICT_ON_SEND = %i[== !=].freeze

        def_node_matcher :even_odd_candidate?, <<~PATTERN
          (send
            {(send $_ :% (int 2))
             (begin (send $_ :% (int 2)))}
            ${:== :!=}
            (int ${0 1}))
        PATTERN

        def on_send(node)
          even_odd_candidate?(node) do |base_number, method, arg|
            replacement_method = replacement_method(arg, method)
            add_offense(node, message: format(MSG, method: replacement_method)) do |corrector|
              correction = "#{base_number.source}.#{replacement_method}?"
              corrector.replace(node, correction)
            end
          end
        end

        private

        def replacement_method(arg, method)
          case arg
          when 0
            method == :== ? :even : :odd
          when 1
            method == :== ? :odd : :even
          end
        end
      end
    end
  end
end

Version data entries

30 entries across 30 versions & 2 rubygems

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