create a password with uppercase, lowercase letters and numbers in ruby

main.rb
def generate_password(length=8)
  chars = ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a
  password = ''
  length.times { password << chars[rand(chars.size)] }
  password
end

# Usage
password = generate_password(10) #=> "wD37bxK9Yt"
239 chars
10 lines

The above implementation of generate_password function generates a password with lowercase letters, uppercase letters and numbers.

It first initializes an array with all the possible alphanumeric characters that we want to use for generating the password. It then sets the length of the password, and generates a random index on the chars array as many times as the password length requires, and appends the character at the resulting index to the password variable.

You can set the password length by passing an argument (an integer) to the generate_password function. By default, if no argument is provided then the function generates an 8 characters long password.

gistlibby LogSnag