Ruby Tuesday – Random::new_seed

Today’s Ruby Tuesday is on Random::new_seed.

Random::new_seed returns a new arbitrary seed value. By generating and capturing the seed value, we can have multiple instances of Random generate the same sequence of random numbers if they were constructed with the same seed.

seed = Random.new_seed
# => 90121465857858294451245401342699150799
Random.new(seed).rand(1_000_000_000)
# => 966720783
Random.new(seed).rand(1_000_000_000)
# => 966720783
Random.new(seed).rand(1_000_000_000)
# => 966720783
Random.new(seed).rand(1_000_000_000)
# => 966720783
Random.new(seed).rand(1_000_000_000)
# => 966720783

In what real world case would we care about capturing a seed?

One example where this becomes useful is creating random sets of test data, especially when one is trying to do a very, very, basic version of generative testing.

def random_list(size, seed=Random.new_seed)
  puts "seed used to generate list was: #{seed}"
  prng = Random.new(seed)
  (1..size).map{|_| prng.rand(1_000_000)}
end


random_list(10)
# seed used to generate list was: 186039884741241642189311371060927079314
# => [333029, 833700, 863953, 325452, 761340, 165891, 818711, 35680, 970562, 926764]
random_list(10)
# seed used to generate list was: 195630211850073328706621905093237636602
# => [414039, 78807, 761787, 93581, 912224, 334025, 139492, 597469, 191557, 637405]
random_list(10)
# seed used to generate list was: 305942993230783695517144566027975028636
# => [459072, 417794, 851547, 51516, 299288, 859682, 514847, 356177, 436546, 63844]

By defining a helper method like random_list above, and having it print out the seed it was using, if we use this list in a test, and that test case fails, we can reproduce the test case by getting the list generated by using the appropriate seed.

random_list(10, 195630211850073328706621905093237636602)
# seed used to generate list was: 195630211850073328706621905093237636602
# => [414039, 78807, 761787, 93581, 912224, 334025, 139492, 597469, 191557, 637405]

–Proctor

Leave a Reply

Your email address will not be published. Required fields are marked *