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: tutorial, script, ruby


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!

Luca said on June 12, 2009:

Thanks you! My random text generator was way longer on more complicated..

Basti said on July 10, 2009:

helped me to save a view minutes... :) thx

Rafael said on August 17, 2009:

thanks !!!

zizhuo said on September 1, 2009:

sorry for being picky here, you seem to missed out the digit 1 in your alphabet. Maybe it should've been chars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ123456789'

Travis said on September 4, 2009:

@zizhuo You'll notice that several characters are missing. I'm leaving out any characters that might look similar and get confused (like lowercase L, number 1, lowercase I, etc.).

Leave a comment:




© 2010 Travis Roberts. All rights reserved.