-1

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

Aziz Shaikh
  • 16,245
  • 11
  • 62
  • 79
Vyacheslav Loginov
  • 3,136
  • 5
  • 33
  • 49

2 Answers2

3

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
Noxx
  • 354
  • 1
  • 19
1

Whoa. I suspect:

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

could be better written as:

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

or:

n.map(&:to_s).zip(a).flatten.join
the Tin Man
  • 158,662
  • 42
  • 215
  • 303