Search code examples
rubydivide-by-zero

ruby prevent division by zero


In some cases such expression

...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)

how to prevent this situation or, maybe, skip loop calculation and continue


Solution

  • if you really just want to skip the current calculation and step forward, the simplest way would be a begin-rescue statement

    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