ddnomad
ddnomad

Reputation: 373

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

I have to surround everything with begin-rescue-end block. I've written code that looks like:

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

The line retry if Dialogs.play_again? caused the following error:

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

Is it possible to make this kind of inline retry to work with if clause without regular if-end multiline approach?

Upvotes: 2

Views: 2073

Answers (3)

steenslag
steenslag

Reputation: 80065

redo is used for control flow.

Quoting the docs: "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."

Upvotes: 0

ddnomad
ddnomad

Reputation: 373

Ok, thank you all for answers! I understood what was a problem, but your workarounds wasn't what I need. Actually, rescue part was for restarting input prompt in case of illegal input from a user, while my 'retry' inside begin was to restart block from another user input (y/n question).

So after some investigation, this code would work flawlessly:

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

And again, thanks for been so awesomely active community. Take care!

Upvotes: 1

spickermann
spickermann

Reputation: 106882

retry works in rescue blocks (or in iterators). And it works with if. Try this:

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

Upvotes: 5

Related Questions