2

I have a uuid (e.g. a3989f5a-1c4b-11e3-8573-0025906a9230) which I need to use as a seed for random number generation in ruby on rails.

Every time a request comes with said uuid, I need to get the same sequence of random numbers generated. Is there any other such function that I am missing here?

Please note: it is very important that for a given uuid, the same sequence of random numbers need to be generated every time.

I have tried using the Kernel.srand() method provided by ruby, however this only accepts integers.

SRack
  • 11,495
  • 5
  • 47
  • 60
user3903418
  • 143
  • 1
  • 1
  • 11

1 Answers1

3

What about

srand "a3989f5a-1c4b-11e3-8573-0025906a9230".tr('-', '').to_i(16)

It will seed Ruby rng from UUID as hex number after we strip dashes

Severin Pappadeux
  • 18,636
  • 3
  • 38
  • 64
  • 1
    This is the correct answer. It works because a UUID is just a hex-encoded 128-bit number (the dashes are just for human readability). It's also worth noting that for OP's use case [`Random.new(seed)`](https://ruby-doc.org/core-2.6.2/Random.html#method-c-new) may be useful to initialize multiple RNGs rather than using `srand` to seed the global RNG. – Jordan Running May 17 '19 at 15:19