views:

1681

answers:

2

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

+19  A: 

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')
quackingduck
+1  A: 

Here is an expression that will use one fewer method call than quackingduck's example.

'%011d' % rand(1e10)

One caveat, 1e10 is a Float, and Kernel#rand ends up calling to_i on it, so for some higher values you might have some inconsistencies. To be more precise with a literal, you could also do:

'%011d' % rand(10_000_000_000) # Note that underscores are ignored in integer literals
nertzy