Reason #118 •
April 28th, 2026
Generating random numbers with rand
The rand method is the simplest way to generate random numbers in Ruby. It can be used in a few different ways:
Ruby
# Generate a random float between 0.0 and 1.0
rand
# => 0.123456789
# Generate a random integer between 0 and 9
rand(10)
# => 7
# Generate a random integer between 1 and 10
rand(1..10)
# => 4
JavaScript
// Generate a random float between 0.0 and 1.0
Math.random();
// => 0.123456789
// Generate a random integer between 0 and 9
Math.floor(Math.random() * 10);
// => 7
// Generate a random integer between 1 and 10
Math.floor(Math.random() * 10) + 1;
// => 4
The seed used for rand can be set with srand, which allows you to generate the same sequence of random numbers:
Ruby
# Set the seed for reproducibility
srand(108)
# These values will be the same on your computer as well:
rand # => 0.23361113598360594
rand # => 0.0343876221032432
History
Both rand and srand have been part of Ruby since its inception in 1995.
The naming originates from the C standard library functions with the same names.
The idea of passing an integer argument to rand to specify an upper bound was likely inspired by the same feature in Perl's rand function.
The ability to pass a Range to rand was added in Ruby 1.9.3, released in 2011, though it had already been available in the more explicit Random.rand, which was introduced in Ruby 1.9.0, released in 2007.