create a password with a custom length and symbols in ruby

To create a password with a custom length and using symbols, you can make use of the SecureRandom module and generate a random string with the desired length and combination of characters. Here's a sample code block:

main.rb
require 'securerandom'

def generate_password(length)
  symbols = '!@#$%^&*()_-+='
  password = SecureRandom.alphanumeric(length - symbols.length)
  password += symbols.split('').shuffle.join('')
end

puts generate_password(10) #=> eD5a5@7K$x
243 chars
10 lines

This method first generates a random alphanumeric string with a length of length - symbols.length. Then it adds the symbols by splitting them into an array of characters, shuffling them, and joining them back together. Finally, it returns the password with a combination of random alphanumeric characters and symbols.

gistlibby LogSnag