create a password with symbols in ruby

main.rb
def generate_password(length = 8)
  symbols = %w(! @ # $ % ^ & * ( ) _ + = - { } [ ] | \ : " ; ' < , > . ? /)
  chars   = ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a + symbols
  password = Array.new(length) { chars.sample }.join("")
end

# Usage Example
# Generate a password of length 10
password = generate_password(10)
puts password
344 chars
11 lines

Explanation:

  • The generate_password method takes an optional parameter length and a list of symbols.
  • The chars variable contains all the possible characters that can be used to generate the password - lowercase and uppercase letters, digits and the provided symbols.
  • The password variable is initialized as an empty string.
  • A loop is run length number of times. In each iteration, a random character is selected from the chars array using the sample method and added to the password array.
  • Finally, the password array is joined to form a string and returned.

gistlibby LogSnag