Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
Kernel#rand
static VALUE
rb_f_rand(int argc, VALUE *argv, VALUE obj)
{
VALUE vmax;
const rb_random_interface_t *rng = &random_mt_if;
rb_random_t *rnd = default_rand_start();
if (rb_check_arity(argc, 0, 1) && !NIL_P(vmax = argv[0])) {
VALUE v = rand_range(obj, rng, rnd, vmax);
if (v != Qfalse) return v;
vmax = rb_to_int(vmax);
if (vmax != INT2FIX(0)) {
v = rand_int(obj, rng, rnd, vmax, 0);
if (!NIL_P(v)) return v;
}
}
return DBL2NUM(random_real(obj, rng, rnd, TRUE));
}
If called without an argument, or if max.to_i.abs == 0, rand returns a pseudo-random floating point number between 0.0 and 1.0, including 0.0 and excluding 1.0.
rand #=> 0.2725926052826416
When max.abs is greater than or equal to 1, rand returns a pseudo-random integer greater than or equal to 0 and less than max.to_i.abs.
rand(100) #=> 12
When max is a Range, rand returns a random number where range.member?(number) == true.
Negative or floating point values for max are allowed, but may give surprising results.
rand(-100) # => 87 rand(-0.5) # => 0.8130921818028143 rand(1.9) # equivalent to rand(1), which is always 0
Kernel.srand may be used to ensure that sequences of random numbers are reproducible between different runs of a program.
Related: Random.rand.
rand(100.0) # => 64 (Integer because max.to_i is 100) Random.rand(100.0) # => 30.315320967824523
Ruby version changes
-
3.0
-
Random::DEFAULTis deprecated since its value is now confusing and it is no longer global, useKernel.rand/Random.randdirectly, or create aRandominstance withRandom.newinstead. [Feature #17351]
-