2009-09-12 3 views
0

Ruby 란 무엇입니까?Ruby에서 if/elsif/else와 함께 조건의 오류 유무 사용하기

if executing the next line wouldn't cause any kind of error then 
    execute this line 
elsif executing the next line wouldn't cause any kind of error then 
    execute this line 
else 

구조 및 예외와 평가를 위해 API 페이지를 읽었으나 지금까지 내 퀘스트에서 실패했습니다.

많은 감사,

스티븐. 다음과 같이

if first_condition 
execute_this_line rescue nil 
elsif second_condition 
execute_that_line rescue nil 
end 

는 결과가됩니다


아사 프 아킨에서 comment에 이어, 나는 다음과 같은 구문을 제안하는거야? first_condition 사실이며이 오류없이 execute_this_line 가능 있다면

, 그것은 execute_this_line됩니다.

first_condition이 true이고 execute_this_line이 일반적으로 을 생성하면 오류로 끝납니다.

첫 번째 조건이 거짓 인 경우 second_condition을 테스트합니다.

오류없이 second_condition이 true이고 execute_that_line이 가능하면오류가 발생하면 execute_that_line 오류가 발생합니다.

그렇지 않으면 끝으로 이동합니다.

if lineA doesn't cause an error 
    execute lineA 
elsif lineB doesn't cause an error 
    execute lineB 
end 

당신이 그것을 원하는 방법으로이 권리인가 :

+2

루비가 미래를 예측하는 방법을 실제로 묻는 중입니까? – Chuck

답변

1

사실, 내가 필요가 있다고 생각 :

if first_condition rescue nil 
execute_this_line 
elsif second_condition rescue nil 
execute_that_line 
end 

이 결과는 다음과 같이 수 있습니까?

first_condition이 참이면 execute_this_line이됩니다.

first_condition이 false이거나 오류가 발생하면 오류를 throw하는 동작없이 second_condition으로 이동합니다.

등 ...

1

나는 명확히하기 위해 의사의 이름을 바꿀거야? 그럼 왜 당신은 당신이 할 수있는 둥지를이 이상을 수행하려면

begin 
    lineA 
rescue 
    error_handling 
ensure 
    lineB 
end 

를 사용하고 확실히 그것은 그것의 몇 가지 새로운 방법을 리팩토링하는 것이 좋습니다 없습니다.

Alternativly 속기 :

valA = lineA rescue StandardError 
lineB if valA.is_a?(Exception) 

을 그리고 당신이 원하는만큼 물론이 같은 여러 번 반복 할 수 있습니다! ;)

+0

감사합니다. Xijo. 네, 재 작성된 의사 코드가 내 의도를 포착하기 때문에 Ruby 코드를 제 작업에 열중시킬 것입니다. 다시 한번 감사드립니다. –

+0

begin ...은 lineA와 lineB를 보장하지만 속기는이를 수정합니다. – rampion