Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby: how to know if script is on 3rd retry?

Tags:

ruby

begin
#some routine
rescue
retry
#on third retry, output "no dice!"
end

I want to make it so that on the "third" retry, print a message.

like image 456
puqt Avatar asked Nov 17 '09 02:11

puqt


3 Answers

Possibly not the best solution, but a simple way is just to make a tries variable.

tries = 0
begin
  # some routine
rescue
  tries += 1
  retry if tries <= 3
  puts "no dice!"
end
like image 137
jtbandes Avatar answered Oct 13 '22 17:10

jtbandes


loop do |i|
  begin
    do_stuff
    break
  rescue
    raise if i == 2
  end
end

or

k = 0
begin
  do_stuff
rescue    
  k += 1
  k < 3 ? retry : raise
end
like image 38
glebm Avatar answered Oct 13 '22 17:10

glebm


begin
  #your code
rescue
  retry if (_r = (_r || 0) + 1) and _r < 4  # Needs parenthesis for the assignment
  raise
end
like image 24
Peder Avatar answered Oct 13 '22 19:10

Peder