create a password with at least one number in ruby

To create a password with at least one number in Ruby, you can use a regular expression to validate the password. Here's an example of a method that generates a random password and ensures that it contains at least one number:

main.rb
def generate_password
  password = SecureRandom.alphanumeric(10)
  until password =~ /\d/
    password = SecureRandom.alphanumeric(10)
  end
  password
end
156 chars
8 lines

In this method, we first generate a random alphanumeric string of length 10 using the SecureRandom.alphanumeric method. We then use a loop to check if the password contains at least one digit. The =~ operator matches the regular expression \d, which represents any digit. If the password doesn't contain a digit, we generate a new one and try again.

You can adjust the length of the password by changing the argument passed to SecureRandom.alphanumeric.

gistlibby LogSnag