Did you know? DZone has great portals for Python, Cloud, NoSQL, and HTML5!
DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5886 posts at DZone. View Full User Profile

Random Password Generator For Ruby

06.04.2006
Email
Views: 15081
  • submit to reddit
        Unfriendly / easily mistaken characters (i o 0 1 l 0) are excluded.

def random_password(size = 8)
  chars = (('a'..'z').to_a + ('0'..'9').to_a) - %w(i o 0 1 l 0)
  (1..size).collect{|a| chars[rand(chars.size)] }.join
end

puts random_password.inspect

(July 14 - Fixed due to comment by friendly commenter below :))    

Comments

Snippets Manager replied on Tue, 2009/01/06 - 8:48am

I've wrote an article about generate random password before user has been saved Please take a look: http://railsgeek.com/2009/1/6/generate-random-password-in-rails

Snippets Manager replied on Wed, 2006/07/12 - 9:49pm

The snipit has a bug. It doesn't actually exclude those hard to see characters because the 0..9 part creates an array of fixnums, not characters/strings. try ('0'..'9').to_a instead.

Snippets Manager replied on Mon, 2012/05/07 - 2:24pm

That's smart, excluding the unfriendlies! How about a random pronouncable password? Not as strong, quite weak actually but a lot more friendly: def random_pronouncable_password(size = 4) c = %w(b c d f g h j k l m n p qu r s t v w x z ch cr fr nd ng nk nt ph pr rd sh sl sp st th tr) v = %w(a e i o u y) f, r = true, '' (size * 2).times do r << (f ? c[rand * c.size] : v[rand * v.size]) f = !f end r end puts random_pronouncable_password.inspect