Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

The documentation for Array#sample 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).

like image 587
steenslag Avatar asked Dec 19 '11 21:12

steenslag


1 Answers

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]
like image 115
Dave Newton Avatar answered Oct 21 '22 16:10

Dave Newton