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() ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With