steenslag steenslag - 1 year ago 74
Ruby Question

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

The documentation for

says it can take an

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
behaves just like
[1,2,3,4,5].sample(3, random: 1..2)

Answer Source

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)

> (1..10000).sample(3, random: NotAtAllRandom)
=> [1, 2, 3]
> (1..10000).sample(3, random: NotAtAllRandom)
=> [1, 2, 3]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download