From: Kirk Haines Date: 2010-02-23T04:12:12+09:00 Subject: Re: Ruby Idiom To Retry open() Upto N Times Before Giving Up On Mon, Feb 22, 2010 at 11:53 AM, Dan wrote: > I write a lot of scripts that I run once or infrequently that uses open-rui. Occasionally I run into a web site that times out or is unavailable for a period of time. My normal solution is to just rerun the script manually at a later time and the problem goes away. What I would like to start doing is rescuing the open() and retrying the open() after a delay. What would be the most idiomatic way to try opening a url say n times before giving up? Here is my crude code for trying twice: > > begin >    open("http://www.example.com/foo.html") >  rescue >    begin >       open("http://www.example.com/foo.html") >     rescue >       #tried twice - giving up >    end > end > Use 'retry'. This is a simple sketch of the concept: irb(main):001:0> n = 0 => 0 irb(main):002:0> begin irb(main):003:1* raise "#{n} tries" irb(main):004:1> rescue irb(main):005:1> n += 1 irb(main):006:1> retry unless n == 3 irb(main):007:1> raise irb(main):008:1> end RuntimeError: 2 tries from (irb):3 from :0 Kirk Haines