How to Generate a 4-digit Random Unique Number Using Ruby?

Hello Friends Today, through this tutorial, I will tell you how to generate a 4-digit random unique OTP number using Ruby Program?

Here’s how to generate a 4-digit random unique otp number using Ruby:

Using `loop` and `SecureRandom`:-

require 'securerandom'

def generate_unique_otp
# Loop until a unique number is generated
loop do
otp = SecureRandom.random_number(10000..9999)
# Check if number already exists in an array (replace `existing_otps` with your logic)
unless existing_otps.include?(otp)
return otp
end
end
end

# Example usage
existing_otps = [1234, 5678] # Replace with your existing OTPs
otp = generate_unique_otp
puts "Generated unique OTP: #{otp}"

Explanation:-

1. This method uses a `loop` to keep generating random numbers until a unique one is found.
2. It uses `SecureRandom.random_number` to generate a random number within the specified range (10000 inclusive to 9999 exclusive) for a 4-digit number.
3. It checks if the generated number already exists in an array of existing OTPs (replace `existing_otps` with your logic to check existing OTPs).
4. If the number is unique, it returns the generated OTP.
5. The example usage demonstrates how to call the function and check for existing OTPs (replace with your actual logic).

Using `Set` (less efficient but simpler):-

require 'set'

def generate_unique_otp
otp_set = Set.new
# Keep generating until set size reaches 1 (unique number)
while otp_set.size < 1
otp = rand(10000..9999)
otp_set.add(otp)
end
otp_set.first
end

otp = generate_unique_otp
puts "Generated unique OTP: #{otp}"

Explanation:-

1. This method uses a `Set` to store generated numbers and leverage its unique element property.
2. It keeps generating random numbers using `rand` within the desired range and adds them to the `otp_set`.
3. The loop continues until the size of the `otp_set` becomes 1, indicating a unique number has been added.
4. Finally, it retrieves the first element from the `otp_set` which is the unique OTP.