In this tutorial, I want to teach you how to generate random numbers with given a number of digits in Ruby. This tutorial is written as an extension to my previous tutorial on how to generate random numbers in ruby. I highly recommend you view that first, before you do this one. You can view that at http://programmingresources.wikia.com/wiki/Ruby-Generate_Random_Numbers

I will be using Random.rand() method here. I will be writing a ruby method here to demonstrate the way you do it.

The way to generate a random number of a given number of digits is to generate a random number below the smallest number with one digit higher than the given number of digits minus the smallest number with the given number of digits and add it to smallest number with the given number of digits. If the statement sound confusing, here is a small example to explain it further.

Let us say that you want to generate a random number with 4 digits. The way the algorithm works is that you take the smallest number with one digit higher than the given number of digits which is 10.000 and subtract the smallest number with the given number of digits which is 1000 and you generate a random number below the resulting subtraction operation which is 9000. Once you get a random number below 9000 add the smallest number with a given number of digits which is 1000 to the random number generated. This will guarantee you that you will always receive a number which has the number of digits that you wanted.

In ruby, the code will be

def generate_random_number_with_n_digits(input_n_digit) smallest_number_of_nplus1_digits = 10**input_n_digit smallest_number_of_n_digits = 10**(input_n_digit-1) random_n_digit_number = Random.rand(smallest_number_of_nplus1_digits-smallest_number_of_n_digits)+smallest_number_of_n_digits return random_n_digit_number end

Copy paste the above method code into irb.It should look something like this and press enter. The code is also available at https://gist.github.com/3189648 for forking.

Randomndigitcodeexample1

Now I am going to call generate_random_number_with_n_digits(4) to get a random 4 digit number

This tutorial was inspired by http://stackoverflow.com/questions/5722881/generate-a-random-number-with-7-digits?lq=1 and the code was rewritten as a method by me. The code of the generate_random_number_with_n_digits() is given to the public domain.

You are watching: Ruby-Generate Random Numbers With Given Number of Digits. Info created by GBee English Center selection and synthesis along with other related topics.