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
Thanks for posting this piece of code. It helped me quite a lot. 10x man
Well written, nice work.
Simply great.
great :)
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
@Dave: Good point! Thanks.
Very useful, thanks!
Leave a comment:
©2008 Travis Roberts. All rights reserved.
![Validate this page for XHTML [Valid XHTML]](/images/xhtml.gif)
![Validate this page for CSS [Valid CSS]](/images/css.gif)
![Validate my RSS feed [Valid RSS]](/images/rss.gif)
Fred said on June 24, 2007:
Just what I was looking for, thanks!