Ruby way: catch division by zero

Andrew picture Andrew · Apr 3, 2011 · Viewed 17.4k times · Source

I have the following method to compute an average:

def compute_average(a,b,c,d,e)
  total = [a,b,c,d,e].sum.to_f
  average = [a, 2*b, 3*c, 4*d, 5*e].sum / total
  average.round(2)
end

It's nothing special, but it has a problem that I expect all average equations have: it might divide by zero if inputs are all zero.

So, I thought of doing this:

def compute_average(a,b,c,d,e)
  total = [a,b,c,d,e].sum.to_f
  if total==0
    average = 0.00
  else
    average = [a, 2*b, 3*c, 4*d, 5*e].sum / total
    average.round(2)
  end
end

... and that works, but it feels kludgy to me. Is there a more elegant, "Ruby Way" to avoid this division by zero problem?

What I'm wishing I had was an "unless then" operator, like...

average = numerator / denominator unless denominator == 0 then 0

Any suggestions?

Answer

Marc-André Lafortune picture Marc-André Lafortune · Apr 3, 2011

You can use nonzero?, as in:

def compute_average(a,b,c,d,e)
  total = [a,b,c,d,e].sum.to_f
  average = [a, 2*b, 3*c, 4*d, 5*e].sum / (total.nonzero? || 1)
end

More people would be more familiar with using the ternary operator (total == 0 ? 1 : total), so that's another possibility.