Method: Kernel#rand
- Defined in:
- random.c
#rand(max = 0) ⇒ Numeric
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.
See also Random.rand.
1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 |
# File 'random.c', line 1672 static VALUE rb_f_rand(int argc, VALUE *argv, VALUE obj) { VALUE vmax; rb_random_t *rnd = rand_start(default_rand()); if (rb_check_arity(argc, 0, 1) && !NIL_P(vmax = argv[0])) { VALUE v = rand_range(obj, rnd, vmax); if (v != Qfalse) return v; vmax = rb_to_int(vmax); if (vmax != INT2FIX(0)) { v = rand_int(obj, rnd, vmax, 0); if (!NIL_P(v)) return v; } } return DBL2NUM(random_real(obj, rnd, TRUE)); } |