title: Ruby: begin, sleep, retry: where to put incrementer
body: <p>I have a method 'rate_limited_follow' that takes my Twitter useraccount and follows all the users in an array 'users'.  Twitter's got strict rate limits, so the method deals with that contingency by sleeping for 15 minutes and then retrying again. (I didn't write this method, rather got it from the Twitter ruby gem api).  You'll notice that it checks to see if the number of attempts are less than the MAX_ATTEMPTS. </p>
  
  <p>My users array has about 400 users that I'm trying to follow. It's adding 15 users at a time (when the rate limits seems to kick in), then sleeping for 15 minutes.  Since I set the MAX_ATTEMPTS constant to 3 (just to test it), I expected it to stop trying once it had added 45 users (3 times 15) but it's gone past that, continuing to add 15 users around every fifteen minutes, so it seems as if num_attempts is somehow remaining below 3, even though it's gone through this cycle more than 3 times.  Is there something I don't understand about the code? Once 'sleep' is finished and it hits 'retry', where does it start again? Is there some reason num_attempts isn't incrementing?</p>
  
  <p>Calling the method in the loop</p>
  
  <pre><code>&gt;&gt; users.each do |i|
  ?&gt;   rate_limited_follow(myuseraccount, i)
  &gt;&gt; end
  </code></pre>
  
  <p>Method definition with constant</p>
  
  <pre><code>MAX_ATTEMPTS = 3
    def rate_limited_follow (account, user)
  
    num_attempts = 0
    begin
      num_attempts += 1
      account.twitter.follow(user)
    rescue Twitter::Error::TooManyRequests =&gt; error
      if num_attempts &lt;= MAX_ATTEMPTS
        sleep(15*60) # minutes * 60 seconds
        retry
      else
        raise
      end
    end
    end
  </code></pre>