class RubbyCop::Cop::Style::NumericPredicate

This cop checks for usage of comparison operators (`==`, `>`, `<`) to test numbers as zero, positive, or negative. These can be replaced by their respective predicate methods. The cop can also be configured to do the reverse.

The cop disregards `nonzero?` as it its value is truthy or falsey, but not `true` and `false`, and thus not always interchangeable with `!= 0`.

@example

# EnforcedStyle: predicate (default)

# bad

foo == 0
0 > foo
bar.baz > 0

# good

foo.zero?
foo.negative?
bar.baz.positive?

@example

# EnforcedStyle: comparison

# bad

foo.zero?
foo.negative?
bar.baz.positive?

# good

foo == 0
0 > foo
bar.baz > 0

Constants

MSG
REPLACEMENTS

Public Instance Methods

on_send(node) click to toggle source
# File lib/rubbycop/cop/style/numeric_predicate.rb, line 57
def on_send(node)
  numeric, replacement = check(node)

  return unless numeric

  add_offense(node, node.loc.expression,
              format(MSG, replacement, node.source))
end

Private Instance Methods

autocorrect(node) click to toggle source
# File lib/rubbycop/cop/style/numeric_predicate.rb, line 81
def autocorrect(node)
  _, replacement = check(node)

  lambda do |corrector|
    corrector.replace(node.loc.expression, replacement)
  end
end
check(node) click to toggle source
# File lib/rubbycop/cop/style/numeric_predicate.rb, line 68
def check(node)
  numeric, operator =
    if style == :predicate
      comparison(node) || inverted_comparison(node, &invert)
    else
      predicate(node)
    end

  return unless numeric && operator && replacement_supported?(operator)

  [numeric, replacement(numeric, operator)]
end
invert() click to toggle source
# File lib/rubbycop/cop/style/numeric_predicate.rb, line 118
def invert
  lambda do |comparison, numeric|
    comparison = { :> => :<, :< => :> }[comparison] || comparison

    [numeric, comparison]
  end
end
parenthesized_source(node) click to toggle source
# File lib/rubbycop/cop/style/numeric_predicate.rb, line 98
def parenthesized_source(node)
  if require_parentheses?(node)
    "(#{node.source})"
  else
    node.source
  end
end
replacement(numeric, operation) click to toggle source
# File lib/rubbycop/cop/style/numeric_predicate.rb, line 89
def replacement(numeric, operation)
  if style == :predicate
    [parenthesized_source(numeric),
     REPLACEMENTS.invert[operation.to_s]].join('.')
  else
    [numeric.source, REPLACEMENTS[operation.to_s], 0].join(' ')
  end
end
replacement_supported?(operator) click to toggle source
# File lib/rubbycop/cop/style/numeric_predicate.rb, line 110
def replacement_supported?(operator)
  if %i[> <].include?(operator)
    target_ruby_version >= 2.3
  else
    true
  end
end
require_parentheses?(node) click to toggle source
# File lib/rubbycop/cop/style/numeric_predicate.rb, line 106
def require_parentheses?(node)
  node.binary_operation? && node.source !~ /^\(.*\)$/
end