Topic: Password generator

When I create a user account, I want to assign them a randomly generated password.  It should be 8 characters long and made up of a mix of numbers and lowercase and uppercase letters. 

I saw a code snippet elsewhere that creates a random string of lowercase letters that I used as a base.  The original code is { (rand(122-97) + 97).chr }.join

Pretty nifty, but only provides for a continuous range of ASCII characters.

So...the code I came up with is as follows

def self.create_default_password
  password_array = []
  8.times do
    x = rand(3)
    case x
      when 0
        y = (rand(122-97) + 97).chr
      when 1
        y = (rand(90-65) + 65).chr
        y = (rand(57-48) + 48).chr
    password_array << y
  return password_array.join

This code works fine, but looks too long and C-ish compared to what I normally see from Ruby.  Is there a better/cleaner way to do this?

Re: Password generator

Hi there,

If I've understood your problem right, this snippet may be helpful. It only uses lowercase characters and numbers, but to add upercase characters you can simple add + ('A'..'Z').to_a.


Re: Password generator

That looks great! I knew there had to be a better way to do it. That's even the site I got my original snippet from, guess I should have looked through it a bit more!

Thanks for the good find!