Skip to content

Instantly share code, notes, and snippets.

@ryancastro
Created November 19, 2015 20:55
Show Gist options
  • Save ryancastro/943ebc72f905121f6acd to your computer and use it in GitHub Desktop.
Save ryancastro/943ebc72f905121f6acd to your computer and use it in GitHub Desktop.
Random key/token generation that is much faster than UUID (at a higher risk, obviously)
# From:
# https://stackoverflow.com/questions/88311/how-best-to-generate-a-random-string-in-ruby
#Generates a random URL-safe key/token much faster than UUID
#Comes with additional risk for high integrity keys, but for many cases it's good enough.
#I'm using it to generate unique file names without the overhead of UUID.
#Occasionally returns a key of length-1
length = 5
p rand(36**length).to_s(36)
#Always returns specified length
length = 5
p (36**(length-1) + rand(36**length - 36**(length-1))).to_s(36)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment