是否可以在 `if` 中使用 `retry` 关键字?

Is it possible to use `retry` keyword inline with `if`?

我必须用 begin-rescue-end 块包围所有内容。我编写的代码如下所示:

begin
  bet = Dialogs.enter_your_bet
  approx.calculate_average_profit(bet)
  approx.print_profits_table
  retry if Dialogs.play_again?
rescue;retry
end

retry if Dialogs.play_again? 行导致了以下错误:

./main:14: Invalid retry
./main: compile error (SyntaxError)

是否可以使这种内联 retryif 子句一起使用而无需常规 if-end 多行方法?

retryrescue 块(或迭代器)中工作。它适用于 if。试试这个:

begin
  bet = Dialogs.enter_your_bet
  approx.calculate_average_profit(bet)
  approx.print_profits_table
rescue
  retry if Dialogs.play_again?
end

好的,谢谢大家的解答!我知道问题出在哪里,但您的解决方法不是我所需要的。实际上,rescue 部分是为了在用户非法输入的情况下重新启动输入提示,而我在 begin 中的 'retry' 是从另一个用户输入(y/n 问题)重新启动块。

经过一些调查,这段代码可以完美运行:

begin
  loop do
    bet = Dialogs.enter_your_bet(gapes[0],gapes[1])
    approx.calculate_average_profit(bet)
    approx.print_profits_table
  break if !Dialogs.play_again?
  end
rescue;retry
end

再次感谢社区如此活跃。保重!

redo用于控制流程。

引用文档:"In Ruby 1.8 you could also use retry where you used redo. This is no longer true, now you will receive a SyntaxError when you use retry outside of a rescue block. See Exceptions for proper usage of retry."