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.

Cialis (Tadalafil) är den främsta konkurrenten till Viagra (Sildenafil) på marknaden för erektil dysfunktion. köpa Cialis i Sverige föredras av många på grund av sin längre varaktighet och anses vara det mest kostnadseffektiva varumärkesbaserade ED-läkemedlet som finns tillgängligt i Sverige. Cialis finns i två varianter: Cialis och Cialis Daily, och fyra olika doseringar: 2,5 mg, 5 mg, 10 mg och 20 mg, erbjuder Cialis också en rad olika alternativ för att passa patientens behov.