Hello Friends Today, through this tutorial, I will tell you how to generate a 6 digit Unique random number in Ruby?
Here are two ways to generate a 6-digit random number in Ruby:
Using `rand` and string manipulation:-
def generate_six_digit_number # Generate a random integer between 100000 and 999999 (inclusive) random_number = rand(1000000) + 100000 # Convert the integer to a string string_number = random_number.to_s # Ensure the string has 6 digits by prepending leading zeros if necessary padded_number = string_number.ljust(6, "0") padded_number.to_i end # Example usage number = generate_six_digit_number puts "Generated 6-digit number: #{number}"
Explanation:-
1. The `generate_six_digit_number` method generates a random integer between 1 million (1000000) and adds 100000 to ensure the range falls within 100000 to 999999.
2. It converts the integer to a string using `to_s`.
3. It uses `ljust(6, “0”)` to pad the string with leading zeros if necessary to reach a length of 6.
4. Finally, it converts the padded string back to an integer using `to_i`.