class RuboCop::Cop::Lint::NumericOperationWithConstantResult
x = 1
# good
x **= 0
x /= x
# bad
1
# good
x ** 0
x / x
# bad
x = 0
# good
x *= 0
# bad
0
# good
x * 0
# bad
@example
a numeric operation.
can’t determine the type of ‘x`. If `x` is an `Array` or `String`, it doesn’t perform
NOTE: This cop doesn’t detect offenses for the ‘-` and `%` operator because it
are handled by `Lint/UselessNumericOperation`.
Other numeric operations that are similarly leftover from debugging or mistakes
These are probably leftover from debugging, or are mistakes.
As such, they can be replaced with that result.
Dividing a number by itself or raising it to the power of 0 will always return 1.
Multiplying a number by 0 will always return 0.
Certain numeric operations have a constant result, usually 0 or 1.
def constant_result?(lhs, operation, rhs)
def constant_result?(lhs, operation, rhs) if rhs.to_s == '0' return 0 if operation == :* return 1 if operation == :** elsif rhs == lhs return 1 if operation == :/ end # If we weren't able to find any matches, return false so we can bail out. false end
def on_op_asgn(node)
def on_op_asgn(node) return unless (lhs, operation, rhs = abbreviated_assignment_with_constant_result?(node)) return unless (result = constant_result?(lhs, operation, rhs)) add_offense(node) do |corrector| corrector.replace(node, "#{lhs} = #{result}") end end
def on_send(node)
def on_send(node) return unless (lhs, operation, rhs = operation_with_constant_result?(node)) return unless (result = constant_result?(lhs, operation, rhs)) add_offense(node) do |corrector| corrector.replace(node, result.to_s) end end