Quick Answer

Handling mathematical operations safely.

Understanding the Issue

Dividing by zero raises ZeroDivisionError. Check denominators before division.

The Problem

This code demonstrates the issue:

Ruby Error
# Problem: Unsafe division
def average(total, count)
  total / count # Error if count == 0
end

The Solution

Here's the corrected code:

Ruby Fixed
# Solution 1: Check zero
def average(total, count)
  return 0 if count.zero?
  total.to_f / count
end

# Solution 2: Rescue
begin
  1 / 0
rescue ZeroDivisionError
  Float::INFINITY
end

Key Takeaways

Validate input before mathematical operations.