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 =(
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 =(
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
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
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