class Random

A pseudo-random number generator with its own state; Random.rand and Kernel#rand draw from a default generator that srand seeds.

Two generators made with the same seed give the same numbers. A Random belongs to the task that made it (Unshareable); the default generator is one for the whole program.

a = Random.new(42)
b = Random.new(42)
a.rand(100) == b.rand(100)   # => true
r = a.rand(1..6)
r >= 1 && r <= 6             # => true

<prelude>:1213

Class methods

def self.new -> Random

A generator seeded from the clock, as .new_seed makes one: #seed tells which.

<prelude>:1218

def self.new(seed: Int) -> Random

A generator seeded with seed.

<prelude>:1220

def self.new_seed -> Int

A new seed from the clock and the process, different at each call.

<prelude>:1222

def self.rand -> Float

A Float from 0.0 up to, not including, 1.0, from the default generator.

<prelude>:1225

def self.rand(max: Int) -> Int

An Int from 0 up to max - 1, from the default generator; ArgumentError unless max is positive.

<prelude>:1228

def self.rand(max: Float) -> Float

A Float from 0.0 up to, not including, max, from the default generator; ArgumentError unless max is positive.

<prelude>:1231

def self.rand(range: Range[Int]) -> Int

An Int in range, from the default generator; ArgumentError for an empty range.

<prelude>:1234

def self.rand(range: Range[Float]) -> Float

A Float from the start of range up to, not including, its end (.. or ...), from the default generator; ArgumentError when the end is below the start. A range whose ends are equal, even an empty one (5.0...5.0), gives its start.

<prelude>:1239

def self.bytes(size: Int) -> Bytes

size random bytes from the default generator; empty for a size of 0 or less.

<prelude>:1242

Methods

def seed -> Int

The seed this generator started from.

<prelude>:1245

def rand -> Float

A Float from 0.0 up to, not including, 1.0.

<prelude>:1247

def rand(max: Int) -> Int

An Int from 0 up to max - 1; ArgumentError unless max is positive.

r = Random.new(1)
n = r.rand(10)
n >= 0 && n < 10    # => true
r.rand(0)           # raises ArgumentError

<prelude>:1257

def rand(max: Float) -> Float

A Float from 0.0 up to, not including, max; ArgumentError unless max is positive.

<prelude>:1260

def rand(range: Range[Int]) -> Int

An Int in range; ArgumentError for an empty range.

<prelude>:1262

def rand(range: Range[Float]) -> Float

A Float from the start of range up to, not including, its end (.. or ...); ArgumentError when the end is below the start. A range whose ends are equal, even an empty one (5.0...5.0), gives its start.

Random.new(1).rand(5.0...5.0)   # => 5.0

<prelude>:1271

def bytes(size: Int) -> Bytes

size random bytes; empty for a size of 0 or less.

<prelude>:1273

def ==(other: Object) -> Bool

Whether other is this same generator. Unlike Ruby, two generators in the same state are not equal.

<prelude>:1276