Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

random

ruby

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

like image 681
quackingduck Avatar asked Aug 29 '08 16:08

quackingduck


People also ask

How do I generate a random number in Ruby?

In Ruby, there are many ways to generate random numbers with various properties. The rand method can be used in 3 ways: Without arguments, rand gives you a floating point number between 0 & 1 (like 0.4836732493) With an integer argument ( rand(10) ) you get a new integer between 0 & that number.

What is Rand in Ruby?

Ruby | Random rand() function Random#rand() : rand() is a Random class method which generates a random value. Syntax: Random.rand() Parameter: Random values. Return: generates a random value.

How do you generate a random 10 digit number in Python?

randrange(10**(n-1),10**n) and random. randrange(1,10) .

How do you generate a random 10 digit number in Java?

long number = (long) Math. floor(Math. random() * 9_000_000_000L) + 1_000_000_000L; Show activity on this post.


2 Answers

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')   
like image 61
quackingduck Avatar answered Oct 02 '22 14:10

quackingduck


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

rand.to_s[2..11]   => "5950281724" 
like image 31
Kreeki Avatar answered Oct 02 '22 13:10

Kreeki