How would i generate a random and unique string in Ruby?

I use this :)

def generate_token(column, length = 64)
  begin
    self[column] = SecureRandom.urlsafe_base64 length
  end while Model.exists?(column => self[column])
end

Replace Model by your model name


SecureRandom.uuid

Will give you a globally unique String. http://en.m.wikipedia.org/wiki/Universally_unique_identifier

SecureRandom.hex 32

Will give a random String, but it's algorithm is not optimised for uniqueness. Of course the chance of collision with 32 digits, assuming true randomness, is basically theoretical. You could make 1 billion per second for 100 years and have only a 50% chance of a collision.


Use Ruby's SecureRandom.hex function with optional number of character you wanted to generate.