Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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() ?

like image 326
dss Avatar asked Mar 02 '23 01:03

dss


1 Answers

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.

like image 69
Silvio Mayolo Avatar answered Mar 05 '23 16:03

Silvio Mayolo