class RuboCop::Cop::Lint::UselessNumericOperation

Certain numeric operations have no impact, being: Adding or subtracting 0, multiplying or dividing by 1 or raising to the power of 1. These are probably leftover from debugging, or are mistakes.

@example

# bad
x + 0
x - 0
x * 1
x / 1
x ** 1

# good
x

# bad
x += 0
x -= 0
x *= 1
x /= 1
x **= 1

# good
x = x

Constants

MSG
RESTRICT_ON_SEND

Public Instance Methods

on_op_asgn(node) click to toggle source
# File lib/rubocop/cop/lint/useless_numeric_operation.rb, line 54
def on_op_asgn(node)
  return unless useless_abbreviated_assignment?(node)

  variable, operation, number = useless_abbreviated_assignment?(node)
  return unless useless?(operation, number)

  add_offense(node) do |corrector|
    corrector.replace(node, "#{variable} = #{variable}")
  end
end
on_send(node) click to toggle source
# File lib/rubocop/cop/lint/useless_numeric_operation.rb, line 43
def on_send(node)
  return unless useless_operation?(node)

  variable, operation, number = useless_operation?(node)
  return unless useless?(operation, number)

  add_offense(node) do |corrector|
    corrector.replace(node, variable)
  end
end

Private Instance Methods

useless?(operation, number) click to toggle source
# File lib/rubocop/cop/lint/useless_numeric_operation.rb, line 67
def useless?(operation, number)
  if number.zero?
    true if %i[+ -].include?(operation)
  elsif number == 1
    true if %i[* / **].include?(operation)
  end
end