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 ...

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.