dss
dss

Reputation: 467

Initialize random number generator in ruby (i.e. set seed)?

How can we set a seed in ruby such that any functions dependent on RNG return the same results (e.g. similar to python's random.seed() ?

Upvotes: 7

Views: 3177

Answers (2)

Silvio Mayolo
Silvio Mayolo

Reputation: 70377

To set the global random seed, you can use Kernel#srand. This will affect future calls to Kernel#rand, the global random number function.

srand(some_number)
rand() # Should get consistent results here

If you want local randomness without affecting the global state, then you want to use the Random class. The constructor of this class takes a random seed.

r = Random.new(some_number)
r.rand() # Should get same result as above

Generally, it can be helpful to pass around specific random states, as it makes mocking and testing much easier and keeps your function effects local.

Upvotes: 8

SteveTurczyn
SteveTurczyn

Reputation: 36880

Use the srand() method

srand(12345)

rand() 
=> 0.9296160928171479
rand()
=> 0.3163755545817859

srand(12345)

rand() 
=> 0.9296160928171479
rand()
=> 0.3163755545817859

Upvotes: 4

Related Questions