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
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!
Thanks you! My random text generator was way longer on more complicated..
helped me to save a view minutes... :) thx
thanks !!!
sorry for being picky here, you seem to missed out the digit 1 in your alphabet. Maybe it should've been chars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ123456789'
@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:
Popular Posts
Search
Tags
actionmailer activerecord ajax apache apple barcamp caching capistrano centos code golf css db delete eager loading ebay email attachment erb flash ftp fun generators get haml helpers ie sucks javascript jquery lightbox lost merb net ftp paperclip passenger php plexus post presentation rails rails machine railsconf redesign rest rjs routes rss ruby ruby on rails safari script sinatra symfony text replacement tips tutorial twitter xhtml
Projects
© 2010 Travis Roberts. All rights reserved.
Fred said on June 24, 2007:
Just what I was looking for, thanks!