DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Random Alphanumeric String Generator

05.28.2006
| 33116 views |
  • submit to reddit
        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. 

# 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

Snippets Manager replied on Wed, 2008/07/02 - 1:44pm

doesn't end up on one line but is a little more readable and doesn't create an array on a range every time collect iterates: alphanumerics = [('0'..'9'),('A'..'Z'),('a'..'z')].map {|range| range.to_a}.flatten (0...25).map { alphanumerics[Kernel.rand(alphanumerics.size)] }.join I'm sure there must be an easier way to gather the alphanumerics that I'm just totally oblivious about.

Snippets Manager replied on Tue, 2008/07/01 - 9:46am

or more flexible regarding character range: (0...size).collect { (45..126).to_a[Kernel.rand(81)].chr }.join here for ascii codes 45 to 126, see http://www.asciitable.com/ for what values to use for which character range. '81' is the difference between 126-45

Snippets Manager replied on Mon, 2008/06/16 - 1:40pm

More readable and extendable is: chars = ('a'..'z').to_a + ('A'..'Z').to_a (0...size).collect { chars[Kernel.rand(chars.length)] }.join

Snippets Manager replied on Fri, 2006/09/15 - 1:14pm

If you wanted to do that in one line, you could do something like: def String.random_alphanumeric(size=16) (1..size).collect { (i = Kernel.rand(62); i += ((i < 10) ? 48 : ((i < 36) ? 55 : 61 ))).chr }.join end