Reputation: 467
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
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
Reputation: 36880
Use the srand()
method
srand(12345)
rand()
=> 0.9296160928171479
rand()
=> 0.3163755545817859
srand(12345)
rand()
=> 0.9296160928171479
rand()
=> 0.3163755545817859
Upvotes: 4