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() ?
Asked
Active
Viewed 1,986 times
2 Answers
8
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.

Silvio Mayolo
- 62,821
- 6
- 74
- 116
-
Could you please explain this in a little more detail in the answer: *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.*? – Timur Shtatland Sep 13 '20 at 15:43
-
This should be the preferred answer - big +1 for mentioning the side-effects of `srand` – johansenja Oct 17 '22 at 15:11
4
Use the srand()
method
srand(12345)
rand()
=> 0.9296160928171479
rand()
=> 0.3163755545817859
srand(12345)
rand()
=> 0.9296160928171479
rand()
=> 0.3163755545817859

SteveTurczyn
- 36,057
- 6
- 41
- 53