|
| 1 | +# Specify How Random Array#sample Is |
| 2 | + |
| 3 | +A typical use of the |
| 4 | +[`sample`](https://ruby-doc.org/core-2.4.0/Array.html#method-i-sample) method |
| 5 | +on [`Array`](https://ruby-doc.org/core-2.4.0/Array.html) will look something |
| 6 | +like this: |
| 7 | + |
| 8 | +```ruby |
| 9 | +> chars = [('a'..'z'), ('A'..'Z'), ('0'..'9')].map(&:to_a).flatten |
| 10 | + |
| 11 | +> chars.sample(6) |
| 12 | +=> ["o", "Z", "X", "i", "8", "Y"] |
| 13 | +``` |
| 14 | + |
| 15 | +By default, this is using `Random` (a pseudo-random number generator) to |
| 16 | +produce a _random_ sampling of elements from your array. |
| 17 | + |
| 18 | +The longer form of this looks like: |
| 19 | + |
| 20 | +```ruby |
| 21 | +> chars.sample(6, random: Random) |
| 22 | +=> ["F", "c", "g", "I", "w", "E"] |
| 23 | +``` |
| 24 | + |
| 25 | +Or to get reproducible results, you can specify the `Random` seed: |
| 26 | + |
| 27 | +```ruby |
| 28 | +> chars.sample(6, random: Random.new(123)) |
| 29 | +=> ["T", "c", "D", "K", "P", "s"] |
| 30 | +``` |
| 31 | + |
| 32 | +If instead you want a cryptographically random sampling of elements from your |
| 33 | +array, you can specify a different random number generator. Such as |
| 34 | +[`SecureRandom`](https://ruby-doc.org/stdlib-2.5.1/libdoc/securerandom/rdoc/SecureRandom.html). |
| 35 | + |
| 36 | +```ruby |
| 37 | +> require 'securerandom' |
| 38 | +=> true |
| 39 | + |
| 40 | +> chars.sample(6, random: SecureRandom) |
| 41 | +=> ["3", "C", "o", "i", "K", "4"] |
| 42 | +``` |
| 43 | + |
| 44 | +The |
| 45 | +[`Array#shuffle`](https://ruby-doc.org/core-2.4.0/Array.html#method-i-shuffle) |
| 46 | +method is another example of a method that can take a `random` option. |
0 commit comments