How does the Ruby’s srand (seed random) method work, and why would one use it?
I often come across Ruby methods that seem to be documented for something other than a human being.
When I read documentation, what I’m looking for is:
- What is it?
- When would I use it?
- How would I use it?
Most of the time I can find a blog post that fills in the gaps, but I came across a Ruby method today where I couldn’t find any useful documentation: srand.
After poking at it for about an hour, here’s my attempt at documentation:
First Some Background on Random Numbers:
Here’s a secret: They’re not really random. (Shhh, don’t tell the anti-Geeks.)
In reality, it’s not possible for a computer to generate a list of truly random numbers. What they do instead is take a seed number, muck around with it a bit until it’s changed to another number, and then spit out that number. Since we don’t know the algorithms used for the “mucking around” bit, even if we knew the seed number, the result would still seem random.
Usually the seed number is generated by the computer using a combonation of elements such as the exact time the random number was requested and the process ID of the program. These elements change constantly, so if you request a random number now, and again 1 millisecond from now (because you’re a really fast typer), the seed number would be different. When the seed number is different, so is the resulting “random” number.
Now, onto how srand works:
What is it?
Srand lets you pick the seed number so you can generate a list of numbers that seems random, but is actually predictable.
When would I use it?
Srand is most likely to be useful during testing.
Let’s say you wanted to test a method that normally uses a random number. In order to test if it’s working correctly, you would have to know what result to expect, and that’s not possible if the random number is generated every time the test is run.
Srand would let you simulate the idea of a program handling random numbers, but with results that are still predictable enough to test.
Or you could:
Use method aliasing to overwrite Ruby’s normal rand method, memorize the first 100 results with your chosen seed number, and convince people that you’re psychic by consistently guessing the next “random” number.
How would I use it?
1. Set the seed number:
2. It will return a list of random numbers that would be generated using that seed number:
3. The next method that uses rand will use the seed number you specify.
for i in 1..10
This will return the same random numbers you got when you first typed srand(1234). In this case it will return the first 10 numbers of the set.
4. The seed you set works only once, so the next time you call rand, it will not use your specified seed number.
for i in 1..10
And that, my dear readers, is how srand works.