1

In Ruby 1.8, retry can be use like:

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

but in Ruby 1.9, it throw an error: Invalid retry, what is the usage of retry in Ruby 1.9? I can't find retry on http://www.ruby-doc.org =(

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Steely Wing
  • 16,239
  • 8
  • 58
  • 54
  • Why not try searching for `ruby + retry`? All sorts of hits come up on Google, which show the syntax for using it. – the Tin Man Feb 19 '13 at 07:35
  • Possible duplicate of http://stackoverflow.com/questions/10063166/what-is-the-purpose-of-redo-and-retry-statements-in-ruby/10064392#10064392 – the Tin Man Feb 19 '13 at 07:37

3 Answers3

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
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
1

Firstly, i believe retry would only work in a begin end block (or implicit begin end block in a method definition). Meaning it would jump back to begin. Not the beginning of a loop. Also as of 1.9 retry only works in a rescue.

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

I think what you are looking for is redo.

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

Be aware that redo will perform the last iteration again. Results being:

0
1
2
3
4
4 # => infinite loop
l__flex__l
  • 1,388
  • 1
  • 16
  • 22
0

Ruby 1.9 supports retry in begin rescue clauses only.

You can use a continuation to replicate the behavior of the old 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
akuhn
  • 27,477
  • 2
  • 76
  • 91