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

String.random

06.23.2008
| 4434 views |
  • submit to reddit
        
class String
  def self.random(length=20)
    chars = ('a'..'z').to_a + ('A'..'Z').to_a + ("0".."9").to_a
    hash = ""; length.times { hash << chars[rand(chars.size)] }; hash
  end
end
    

Comments

Snippets Manager replied on Tue, 2008/03/11 - 10:39am

@ChronicStar: I think you win an award there... @fatlotus: Yes, it would probably be better to cache the characters beforehand.

Snippets Manager replied on Fri, 2008/06/27 - 2:54pm

How about this? class String def self.random(length=20) @@chars ||= ('a'..'z').to_a + ('A'..'Z').to_a + ("0".."9").to_a (1..length).map { @@chars[rand(@@chars.size)] }.to_s end end

Snippets Manager replied on Wed, 2007/05/16 - 11:08pm

How about... (1..length).map{i=rand(62);(i+(i<10?48:i<36?55:61)).chr}*'' Cryptic, but eh.