create a password with uppercase letters and lowercase letters in ruby

To create a password with a random combination of uppercase and lowercase letters, you can use the SecureRandom module in Ruby to generate a random string of the desired length, then convert the string to uppercase or lowercase:

main.rb
require 'securerandom'

def generate_password(length = 8)
  lower = ("a".."z").to_a
  upper = ("A".."Z").to_a
  num = ("0".."9").to_a
  symbols = %w{! @ # $ % ^ & * ( ) - _ = + [ ] \ { } ; : " ' < > , . ? /}

  all = lower + upper + num + symbols

  password = ""

  length.times do
    password << all.sample
  end

  password = password.downcase if rand(2) == 0 # randomly change case
  password = password.upcase if rand(2) == 0

  return password
end

# Example usage
password = generate_password(10)
puts password
519 chars
26 lines

This code generates an array of lowercase letters, uppercase letters, numbers, and symbols. It then randomly selects characters from this array and concatenates them into a password of the desired length. Finally, it randomly changes the case of the password (either uppercase or lowercase) for added security. The password is returned as a string.

gistlibby LogSnag