메서드를 수행 할 때 오류가 발생하는 것처럼 사용자 지정 예외를 제기하고 여러 번 구조해야합니다. 나는 그것이 결과적으로 예외적 인 결과를 가져올 것이라는 것을 알고있다.올바른 결과가 나올 때까지 반복적으로 예외를 처리하는 방법은 무엇입니까?
begin/rescue/end를 사용하면 예외가 발생하고 구조 블록이 호출 된 것처럼 보입니다. 예외가 다시 발생하면 프로그램은 begin/rescue/end 블록을 떠나고 오류로 인해 프로그램이 종료됩니다. 적절한 결과에 도달 할 때까지 프로그램을 계속 실행하려면 어떻게해야합니까? 또한, 나는 무슨 일이 일어나고 있는지에 대해 내 생각이 틀린가?
기본적으로 내가하고 싶은 것은 (가능한 한 코드의 DRY로 ...이 코드는 설명하기위한 것이고 구현해야하는 것은 아닙니다.)
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?
orientation = rand(2) == 1 ? :vertical : :horizontal
cell_coords = [rand(10), rand(10)]
place_ship(ship, orientation, cell_coords)
rescue OverlapError
orientation = rand(2) == 1 ? :vertical : :horizontal
cell_coords = [rand(10), rand(10)]
place_ship(ship, orientation, cell_coords)
rescue OverlapError
orientation = rand(2) == 1 ? :vertical : :horizontal
cell_coords = [rand(10), rand(10)]
place_ship(ship, orientation, cell_coords)
#keep rescuing until the result is exception free
end
end
감사합니다. 둘 다 내 질문에 대답하고 구현할 수있는 더 좋은 방법을 찾게했습니다. –