How do I generate a random 10 digit number in ruby?

Additionally, how can I format it as a string padded with zeros?


Solution 1:

To generate the number call rand with the result of the expression "10 to the power of 10"

rand(10 ** 10)

To pad the number with zeros you can use the string format operator

'%010d' % rand(10 ** 10)

or the rjust method of string

rand(10 ** 10).to_s.rjust(10,'0')  

Solution 2:

I would like to contribute probably a simplest solution I know, which is a quite a good trick.

rand.to_s[2..11] 
 => "5950281724"