Additionally, how can I format it as a string padded with zeros?
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.
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.
randrange(10**(n-1),10**n) and random. randrange(1,10) .
long number = (long) Math. floor(Math. random() * 9_000_000_000L) + 1_000_000_000L; Show activity on this post.
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')
I would like to contribute probably a simplest solution I know, which is a quite a good trick.
rand.to_s[2..11] => "5950281724"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With