Random Alphanumeric String Generator

Submitted by:David Villa

Date added:06 July, 2011

Category:Rails

This allows you to do String.random_alphanumeric(num) to get a random string that is num characters long. Useful for generating random identifier keys.

Tags: alphanumeric string generator

Code Snippet:

# Returns a random alphanumeric string of arbitrary size.

def String.random_alphanumeric(size=16)
s = ""
size.times { s << (i = Kernel.rand(62); i += ((i < 10) ? 48 : ((i < 36) ? 55 : 61 ))).chr }
s
end
 
 

Comments