How to use Array # sample (n, random: rng) syntax?

The documentation for Array#sample says it can accept rng :

If rng is specified, it will be used as a random number generator.

How can a range function as a random number generator or why is it useful?

Also, the hash form suggests other options, but I can not find anything about them. The attempt [1,2,3,4,5].sample(3) behaves exactly the same as the [1,2,3,4,5].sample(3, random: 1..2) .

+7
source share
1 answer

The argument must be a random number generator (RNG).

If not specified, it defaults to implementing the Ruby stock.

It can be replaced with an arbitrary RNG, as well as random:

 class NotAtAllRandom def self.rand(x=0) 0 end end > (1..10000).sample(3, random: NotAtAllRandom) => [1, 2, 3] > (1..10000).sample(3, random: NotAtAllRandom) => [1, 2, 3] 
+8
source

All Articles