1

在 Ruby 1.8 中,retry可以像这样使用:

for i in 0..4
  puts i
  retry if i == 4
end

但是在 Ruby 1.9 中,它会抛出一个错误: Invalid retry, what is used retryin Ruby 1.9? retry我在http://www.ruby-doc.org上找不到=(

4

3 回答 3

6

It is for retrying failed operations (when you catch an exception)

n = 0
begin
  puts 'Trying to do something'
  raise 'oops'
rescue => ex
  puts ex
  n += 1
  retry if n < 3
end
puts "Ok, I give up"


# >> Trying to do something
# >> oops
# >> Trying to do something
# >> oops
# >> Trying to do something
# >> oops
# >> Ok, I give up
于 2013-02-19T07:00:26.047 回答
1

首先,我相信重试只能在开始结束块(或方法定义中的隐式开始结束块)中工作。这意味着它会跳回开始。不是循环的开始。同样从 1.9 开始,重试仅在救援中有效。

begin # should jump here
  for i in 4..0
    puts i
    4 / i
  end
rescue
  retry
end

我认为您正在寻找的是重做。

for i in 0..4
  puts i
  redo if i == 4
end

请注意,重做将再次执行最后一次迭代。结果是:

0
1
2
3
4
4 # => infinite loop
于 2014-08-18T12:56:55.857 回答
0

Ruby 1.9 仅支持retryinbegin rescue子句。

您可以使用延续来复制旧的行为retry

require 'continuation'

def with_retry
  loop { callcc { |cc| def cc.retry; call; end; yield cc; return }}
end

with_retry do |cc|
  for n in 1..4
    puts n
    cc.retry if n == 4
  end
end
于 2016-12-20T22:04:45.337 回答