To create a password with a custom length, uppercase letters, and lowercase letters in Ruby, you can use the following code:
main.rb379 chars12 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