steenslag steenslag - 1 month ago 8
Ruby Question

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

The documentation for

says it can take an
rng
:


If rng is given, it will be used as the random number generator.


How can a range function as a random number generator, or why is such thing useful?

Also the hash form suggests there are other options, but I can't find anything about them. Trying out
[1,2,3,4,5].sample(3)
behaves just like
[1,2,3,4,5].sample(3, random: 1..2)
.

Answer

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

If one is not provided, it defaults to the "stock" Ruby implementation.

It can be replaced with an arbitrary RNG, like one that isn't at all 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]
Comments