我讀過這段代碼,我想了解如何使用retry
,我無法想到使用。別人怎麼使用它?用於重試功能的用例?
#!/usr/bin/ruby
for i in 1..5
retry if i > 2
puts "Value of local variable is #{i}"
end
我讀過這段代碼,我想了解如何使用retry
,我無法想到使用。別人怎麼使用它?用於重試功能的用例?
#!/usr/bin/ruby
for i in 1..5
retry if i > 2
puts "Value of local variable is #{i}"
end
有幾種用例。這裏有一本來自Programming Ruby的書
@esmtp = true
begin
# First try an extended login. If it fails because the
# server doesn't support it, fall back to a normal login
if @esmtp then
@command.ehlo(helodom)
else
@command.helo(helodom)
end
rescue ProtocolError
if @esmtp then
@esmtp = false
retry
else
raise
end
end
另一個常見的情況是電子郵件傳遞。您可能需要重試SMTP傳遞N次,在每次重試之間添加sleep
以避免由網絡連接導致的臨時問題。
我認爲這不是很好......如果helo方法出現協議錯誤,該怎麼辦?當我再次做的事情是一樣的時候,似乎應該使用重試。 – nroose
我使用它作爲api調用第三方web api的模塊,所以如果失敗,我再重試2次。
我不知道重試也可用循環。我只用它來救援:做一些事情拯救例外,做一些不同的事情,然後重試。例如:http://www.wikidlabs.com/ruby-stuff-use-retry-to-restart-a-begin-rescue-block/ – Wukerplank
'retry'在1.8中循環工作。這個功能在1.9中消失了,所以它現在只能在'rescue'中運行。 「Ruby編程語言」一書中說:「......但是,在Ruby 1.8中,重試有另一個用處:它從頭開始重新啓動基於迭代器的迭代(或任何方法調用)。這種重試語句的使用非常少見,並且已經從Ruby 1.9中的語言中刪除。因此,它應該被視爲已棄用的語言功能,不應在新代碼中使用。' –