Never been to DZone Snippets before?

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

Random password generator for Ruby (See related posts)

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 on this post

remvee posts on Jun 05, 2006 at 10:50
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
jwarchol posts on Jul 12, 2006 at 21:51
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.

You need to create an account or log in to post comments to this site.


Click here to browse all 5141 code snippets

Related Posts