红宝石防止零除

时间:2012-09-13 20:04:06

标签: ruby divide-by-zero

在某些情况下这样的表达

...some loop
  solution = n[0].to_s+a[0]+n[1].to_s+a[1]+n[2].to_s+a[2]+n[3].to_s+a[3]+n[4].to_s+a[4]+n[5].to_s 
  puts solution if eval(solution) == 100

#=> `eval': divided by 0 (ZeroDivisionError)

如何防止这种情况,或者,可能跳过循环计算并继续

2 个答案:

答案 0 :(得分:3)

如果你真的只想跳过当前的计算并向前迈进,最简单的方法就是开始救援声明

loop do
  begin
    solution = n[0].to_s+a[0]+n[1].to_s+a[1]+n[2].to_s+a[2]+n[3].to_s+a[3]+n[4].to_s+a[4]+n[5].to_s
    puts solution if eval(solution) == 100
  rescue ZeroDivisionError
    # catch error
  end
end

答案 1 :(得分:1)

哇。我怀疑:

n[0].to_s+a[0]+n[1].to_s+a[1]+n[2].to_s+a[2]+n[3].to_s+a[3]+n[4].to_s+a[4]+n[5].to_s

AKA:

n[0].to_s +
a[0] +
n[1].to_s +
a[1] +
n[2].to_s +
a[2] +
n[3].to_s +
a[3] +
n[4].to_s +
a[4] +
n[5].to_s

可以更好地写成:

n[0..5].map(&:to_s).zip(a[0..4]).flatten.join

或:

n.map(&:to_s).zip(a).flatten.join