Sometimes, after a few pints in a respectable gathering of Rubyists, someone will ask me “what is the most undervalued module in the Ruby standard library?” There are many possible answers, of course, and some favoritism is to be expected. Piotr Szotkowski, who untimely passed away this summer, did a wonderful talk on the topic a wee while back. My personal answer to that question, however, would be Random. To me, Random is a unsung hero of a very large slice of the work we need to do in web application, especially so when we need things to be deterministic and testable. So, let’s examine this little jewel a bit closer. 🧭 I am currently available for contract work. Hire me to help make your Rails app better! The various random sources A Random and its far-removed cousin SecureRandom are interfaces to random number generators, or sources of entropy. I won’t bother you with too many details, but the simplest use for an RNG is simulating a dice roll: random_side = Random.rand(1..6) You can also do the same using SecureRandom of course (there is quite a bit of overlap between Random and SecureRandom but not all of it): random_side = SecureRandom.rand(1..6) There is a substantial difference between them, though. SecureRandom latches onto the entropy source of the operating system, and reads the random bytes from that source (it is a file, usually). Therefore, SecureRandom is not deterministic and not repeatable. Random, however, is - which is where it becomes useful. It is an implementation of something known as the Mersenne twister and is built to produce a sequence of pseudorandom values which is achieved by various techniques of bit mixing and twiddling. A Random is stateful It is, after all, a sequence. A seeded Random object is able to produce pseudo-random numbers (or output) indefinitely, by revolving its internal byte bag - starting at the seed. You can think of it as an infinite Range: counter = (0..).each counter.next # First call returns 0, second - 1, third -...
First seen: 2025-10-10 06:23
Last seen: 2025-10-10 06:23