Generate random text with Ruby

Published on June 7, 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: ruby, script


Fred said on June 24, 2007:

Just what I was looking for, thanks!

Dan said on June 27, 2007:

Thanks for posting this piece of code. It helped me quite a lot. 10x man

Mark said on August 25, 2007:

Well written, nice work.

Iñaki said on October 4, 2007:

Simply great.

primary0 said on March 26, 2008:

great :)

Dave Burt said on April 29, 2008:

It's a nice and simple idea, but your code is buggy. You'll never get a 9. Also, instead of downto, just use Integer#times: chars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789' password = '' length.times { password << chars[rand(chars.size)] } password

Travis said on April 29, 2008:

@Dave: Good point! Thanks.

Jason said on April 30, 2008:

Very useful, thanks!

Leave a comment:




©2008 Travis Roberts. All rights reserved.