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

Here's a code snippet for generating a random password with uppercase, lowercase letters, numbers, and symbols in Ruby:

main.rb
def generate_password(length = 8)
  symbols = %w(! @ # $ % ^ & *)
  chars = [('a'..'z'), ('A'..'Z'), (0..9)].map(&:to_a).flatten + symbols
  password = ''
  length.times { password += chars.sample.to_s }
  password
end
219 chars
8 lines

This method accepts an optional length parameter (defaulting to 8), and generates a random password using an array of character sets. The chars array is created by merging all the desired character sets (lowercase letters, uppercase letters, numbers, and symbols) using the + operator.

The password variable is then updated by adding a randomly-selected character from the chars array using the sample method. This process is repeated for the desired length of the password.

This method can be used to generate strong, unique passwords for user authentication purposes. However, it's important to note that password security is just one aspect of a secure application. It's also important to enforce password policies (such as minimum length requirements) and to properly store and encrypt passwords.

gistlibby LogSnag