Thursday, February 10, 2011

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

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.

  • 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
    
    From jtbandes
  • 3.times do
      begin
        ...
      rescue
        ...
      end
      break
    end
    

    or

    k = 0
    begin
    #some routine
    rescue    
      k += 1
      retry if k < 3
      # no dice
    end
    
    DigitalRoss : The best of the early answers...
    From glebm
  • 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
    
    From Justice
  • 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.

0 comments:

Post a Comment