You can use retry
:
ships.each do |ship|
begin
orientation = rand(2) == 1 ? :vertical : :horizontal
cell_coords = [rand(10), rand(10)]
place_ship(ship, orientation, cell_coords)
rescue OverlapError #if overlap error happens twice in a row, it leaves?
retry
end
end
Anyway, I have to say that you should not use exceptions as control flow. I will recommend you , if place_ship
is expected to fail, it should return true
/false
result, and you should include the code in a standard do while
loop.