s

Generate random text with Ruby

Jun 07, 2007

UPDATE: Changed the generate_password method slightly based on commenter Dave Burt's suggestion.

I'm working on a project where the user can reset their password if they've forgotten it. So, I need to generate a random password and email it to them so they can login and change it. Fortunately, I found this neat little Ruby snippet that will generate random text of a given length:

def generate_password(length=6)
  chars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ23456789'
  password = ''
  length.times { |i| password << chars[rand(chars.length)] }
  password
end

Some examples:

generate_password
>> U48ydn

generate_password(10)
>> QzWXdAkDy5

Tagged: rubyscripttutorial