title: Generating a unique, but apparently random, identifier without loop+retry
body: <p>I'm trying to come with an algorithm to generate unique nonsequential tokens for a model in my rails app.</p>
  
  <p>For instance:</p>
  
  <pre><code>MyModel.create.token #=&gt; '183685'
  MyModel.create.token #=&gt; '456873'
  MyModel.create.token #=&gt; '813870'
  </code></pre>
  
  <p>The only way I can think to handle this is to create a random thing, check for a clash, and retry.  This seems kind of code smelly to me, in a bute force kind of way.</p>
  
  <pre><code>class MyModel &lt; ActiveRecord::Base
    before_create :set_token
  
    def set_token
      existing_model_count = nil
  
      # Loop while we have a token that already belongs to an existing model.
      while existing_model_count.nil? || existing_model_count &gt; 0
        random_token = TokenGenerator.random_token
        existing_model_count = MyModel.where(token: random_token).count
      end
  
      # Loop exited, meaning we found an unused token.
      self.token = random_token
    end
  end
  </code></pre>
  
  <p>Is there a better way to do this that doesn't involve a <code>while</code> loop which will iterate an unknown number of times?</p>
  
  <hr>
  
  <p><em>While the examples here are ruby, this is sort of generic algorithmic issue which can apply to any language, so solutions in other languages are welcome.</em></p>