The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)

5.28. Generating Random Numbers

If a pseudorandom number is good enough for you, you're in luck. This is what most language implementations supply you with, and Ruby is no exception.

The Kernel method rand returns a pseudorandom floating point number x such that x>=0.0 and x<1.0. For example (note yours will vary)

a = rand # 0.6279091137

If it is called with an integer parameter max, it returns an integer in the range 0...max (noninclusive of the upper bound). For example (note yours will vary)

n = rand(10) # 7

If we want to seed the random number generator, we can do so with the Kernel method srand, which takes a single numeric parameter. If we pass no value to it, it will construct its own using (among other things) the time of day. If we pass a number to it, it will use that number as the seed. This can be useful in testing, when we want a repeatable sequence of pseudorandom numbers from one script invocation to the next.

srand(5) i, j, k = rand(100), rand(100), rand(100) # 26, 45, 56 srand(5) l, m, n = rand(100), rand(100), rand(100) # 26, 45, 56

Категории