2

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?

sawa
  • 165,429
  • 45
  • 277
  • 381
ddnomad
  • 373
  • 3
  • 15

3 Answers3

5

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
spickermann
  • 100,941
  • 9
  • 101
  • 131
  • The `rescue` block is only called if an exception is raised. – Stefan Dec 02 '15 at 10:02
  • @Stefan yes, you're right. And that's why this implementation is not what I want (my mistake, maybe I should explain what I need more clearly). I selfanswered this question with a possible workaround to make things work. – ddnomad Dec 02 '15 at 10:13
1

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!

ddnomad
  • 373
  • 3
  • 15
  • `if !Dialogs.play_again?` is equivalent to `unless Dialogs.play_again?` – Stefan Dec 02 '15 at 10:11
  • @Stefan yes, surly. Yet I have a terrible headache using 'unless' keyword, so I got rid of it :) – ddnomad Dec 02 '15 at 10:14
  • Note that you are `retry`-ing the whole `loop` in case of an exception. I would wrap the `loop`'s body in a `begin-rescue-end` block and remove the `retry`. – Stefan Dec 02 '15 at 10:22
  • @Stefan in my particular case it's ok, as I store all the necessary info in approx object instance that was created before. But again - thanks for an observation. – ddnomad Dec 02 '15 at 10:27
0

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."

steenslag
  • 79,051
  • 16
  • 138
  • 171