Skip to content

Latest commit

 

History

History
46 lines (34 loc) · 1.25 KB

specify-how-random-array-sample-is.md

File metadata and controls

46 lines (34 loc) · 1.25 KB

Specify How Random Array#sample Is

A typical use of the sample method on Array will look something like this:

> chars = [('a'..'z'), ('A'..'Z'), ('0'..'9')].map(&:to_a).flatten

> chars.sample(6)
=> ["o", "Z", "X", "i", "8", "Y"]

By default, this is using Random (a pseudo-random number generator) to produce a random sampling of elements from your array.

The longer form of this looks like:

> chars.sample(6, random: Random)
=> ["F", "c", "g", "I", "w", "E"]

Or to get reproducible results, you can specify the Random seed:

> chars.sample(6, random: Random.new(123))
=> ["T", "c", "D", "K", "P", "s"]

If instead you want a cryptographically random sampling of elements from your array, you can specify a different random number generator. Such as SecureRandom.

> require 'securerandom'
=> true

> chars.sample(6, random: SecureRandom)
=> ["3", "C", "o", "i", "K", "4"]

The Array#shuffle method is another example of a method that can take a random option.