begin
#some routine
rescue
retry
#on third retry, output "no dice!"
end
我想讓它在「第三次」重試時打印一條消息。ruby:如何知道腳本是否在第三次重試?
begin
#some routine
rescue
retry
#on third retry, output "no dice!"
end
我想讓它在「第三次」重試時打印一條消息。ruby:如何知道腳本是否在第三次重試?
可能不是最好的解決方案,但一個簡單的方法就是製作一個tries
變量。
tries = 0
begin
# some routine
rescue
tries += 1
retry if tries <= 3
puts "no dice!"
end
loop do |i|
begin
do_stuff
break
rescue
raise if i == 2
end
end
或
k = 0
begin
do_stuff
rescue
k += 1
k < 3 ? retry : raise
end
最好的早期答案... – DigitalRoss 2009-11-17 02:31:26
我喜歡這些替代品的第一個,因爲它易於記憶和閱讀。但它不會引發最後一次嘗試的錯誤! – Peder 2011-08-24 09:53:56
沒錯,第一個不適合大多數網絡代碼,但可以在不引發異常時使用。 – glebm 2011-09-01 12:03:28
class Integer
def times_try
n = self
begin
n -= 1
yield
rescue
raise if n < 0
retry
end
end
end
begin
3.times_try do
#some routine
end
rescue
puts 'no dice!'
end
寶石attempt被設計用於此,並且提供的嘗試之間等待的選項。我自己並沒有使用它,但它似乎是一個好主意。正如其他人已經證明的那樣,這是塊擅長的東西。
begin
#your code
rescue
retry if (_r = (_r || 0) + 1) and _r < 4 # Needs parenthesis for the assignment
raise
end
還有另一個名爲retry-this的寶石,可以幫助這樣的事情。
ruby-1.9.2-p0 > require 'retry-this'
ruby-1.9.2-p0 > RetryThis.retry_this(:times => 3) do |attempt|
ruby-1.9.2-p0 > if attempt == 3
ruby-1.9.2-p0 ?> puts "no dice!"
ruby-1.9.2-p0 ?> else
ruby-1.9.2-p0 > puts "trying something..."
ruby-1.9.2-p0 ?> raise 'an error happens' # faking a consistent error
ruby-1.9.2-p0 ?> end
ruby-1.9.2-p0 ?> end
trying something...
trying something...
no dice!
=> nil
這樣一個創業板的好東西,而不是原始begin..rescue..retry的是,我們能夠避免無限循環或引入一個變量只是爲了這個目的。
def method(params={})
tries ||= 3
# code to execute
rescue Exception => e
retry unless (tries -= 1).zero?
puts "no dice!"
end
Proc.class_eval do
def rescue number_of_attempts=0
@n = number_of_attempts
begin
self.call
rescue => message
yield message, @n if block_given?
@n -= 1
retry if @n > 0
end
end
end
然後你可以使用它作爲:
-> { raise 'hi' }.rescue(3)
-> { raise 'hi' }.rescue(3) { |m, n| puts "message: #{m},
number of attempts left: #{n}" }
而是重試,把這件事情在3.times循環? – 2009-11-17 02:13:11
你的意思是在一個循環中重試三次? – puqt 2009-11-17 02:15:05