Random password generation with Ruby

Suppose we want to generate a random, robust and fairly secure password using Ruby then we create a "random_password" function that returns a password with 12 characters or if we want one with more or less we have to pass this value as a parameter.

First we define the range of characters allowed for the password

$CHARS = ('0'..'9').to_a + ('A'..'Z').to_a + ('a'..'z').to_a + ('#'..'&').to_a + (':'..'?').to_a

then the function

def random_password(length=12)
  p=''
  (0..length).each do
    p+=$CHARS[rand($CHARS.size)]
  end
  return p
end

Finally, just use the newly created function to have the random password:

puts random_password
puts random_password(15)
test_pwd=random_password
puts test_pwd

Leave a Reply

Your email address will not be published. Required fields are marked *

2 × = 20