Generate Random Password Using Ruby



When we want to protect our online accounts or protect sensitive data, we use a strong password. Creating a secure, random password is a little complex but in Ruby, we can easily and quickly generate a random password. In this article, we are going to discuss how we can generate a random password using ruby, different approaches, example codes, and outputs.

Generate a Random Password Using Ruby

Since the code generates random passwords, the output will vary each time you run it, and it will not match the previously shown examples.

Using Ruby's rand Method

The rand method in Ruby is a basic way to generate random numbers. we can use it to pick random characters for our password. We create a string of chars containing all the characters we want in our password. We then use a loop to pick random characters from chars and build our password. The rand(chars.size) generates a random index to select a character. This method is simple but not the most secure because randomness is not very strong.

Example Code

Below is an example code for the above approach.

def simple_random_password(length)
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
password = ''
length.times {
  password << chars[rand(chars.size)]
}
password
end

puts simple_random_password(10)

Output

SEbaHpzVpj

Using the SecureRandom Module

Ruby offers the SecureRandom module for a more secure password. This module generates random numbers and strings in a way that's more secure, making it harder for anyone to guess the password. We use SecureRandom.alphanumeric(length) to generate a string of random alphanumeric characters. This method is quick and gives us a more secure password.

Example Code

Below is an example code for the above approach.

require 'securerandom'

def secure_random_password(length = 10)
SecureRandom.alphanumeric(length)
end

puts secure_random_password(12)

Output

sichrbnWyngc

Custom Password Generator

If we want to create a password with a mix of letters, numbers, and symbols, we can create a custom password generator. We expand the chars string to include symbols like !@#$%^&*(). The method creates an array of random characters and then joins them into a single string.

Example Code

Below is an example code for the above approach.

def custom_random_password(length = 12)
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()'
password = Array.new(length) {
  chars[rand(chars.size)]
}.join
end

puts custom_random_password(15)

Output

!)M&8SGha#4YNwf
Updated on: 2024-11-21T14:02:19+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements