ZeroDivisionError
RubyERRORNotableMath
Integer division by zero
Quick Answer
Guard divisors with a zero check before dividing, or use Float arithmetic when infinity is an acceptable result.
What this means
Raised when an integer is divided by zero. Note that Float division by zero does not raise this error — it returns Float::INFINITY or NaN instead.
Why it happens
- 1Dividing an integer by a variable that evaluates to zero
- 2Modulo operation (%) with a zero divisor
- 3Computed denominators in financial or statistical code
Fix
Guard divisor before dividing
Guard divisor before dividing
def safe_divide(a, b) return 0 if b.zero? a / b end
Why this works
b.zero? returns true when b == 0, preventing the division from executing.
Code examples
Reproducing the errorruby
10 / 0 # ZeroDivisionError: divided by 0
Float division returns Infinityruby
10.0 / 0 # => Infinity (no error) 0.0 / 0 # => NaN (no error)
Rescue ZeroDivisionErrorruby
begin result = numerator / denominator rescue ZeroDivisionError result = 0 end
Same error in other languages
Sources
Official documentation ↗
Ruby Core Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev