tags:

views:

228

answers:

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

+4  A: 

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
jtbandes
+4  A: 
3.times do
  begin
    ...
  rescue
    ...
  end
  break
end

or

k = 0
begin
#some routine
rescue    
  k += 1
  retry if k < 3
  # no dice
end
glebm
The best of the early answers...
DigitalRoss
A: 
class Integer
  def times_try
    n = self
    begin
      n -= 1
      yield
    rescue
      raise if n < 0
      retry
    end
  end
end

begin
  3.times_try do
    #some routine
  end
rescue
  puts 'no dice!'
end
Justice
+1  A: 

The gem attempt is designed for this, and provides the option of waiting between attempts. I haven't used it myself, but it seems to be a great idea.

Otherwise, it's the kind of thing blocks excel at, as other people have demonstrated.

Andrew Grimm