create a password with a custom length, uppercase letters and lowercase letters in ruby

To create a password with a custom length, uppercase letters, and lowercase letters in Ruby, you can use the following code:

main.rb
require 'securerandom'

def generate_password(length)
  password = ''
  while password.length < length
    password += SecureRandom.alphanumeric(1).upcase if password.length.zero? || password.match(/[a-z]/)
    password += SecureRandom.alphanumeric(1).downcase if password.length.zero? || password.match(/[A-Z]/)
    password += SecureRandom.alphanumeric(1)
  end
  password
end
379 chars
12 lines

Here, we are using the SecureRandom library to generate random alphanumeric characters. We start by initializing an empty string for the password. We then loop until the password length reaches the desired length. Inside the loop, we check if the password is empty, or if it already contains a lowercase or uppercase letter. If it does, we add a character of the opposite case using SecureRandom.alphanumeric(1).upcase or .downcase. Otherwise, we add a random alphanumeric character without regard for its case using SecureRandom.alphanumeric(1).

Finally, we return the generated password. You can specify the desired password length by calling generate_password with an argument representing the desired length, like generate_password(12) for a 12-character password.

gistlibby LogSnag