diff --git a/README.md b/README.md index 2076c0f..04d7ce3 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1396 TILs and counting..._ +_1397 TILs and counting..._ --- @@ -1187,6 +1187,7 @@ _1396 TILs and counting..._ - [Single And Double Quoted String Notation](ruby/single-and-double-quoted-string-notation.md) - [Skip Specific CVEs When Auditing Your Bundle](ruby/skip-specific-cves-when-auditing-your-bundle.md) - [Specify Dependencies For A Rake Task](ruby/specify-dependencies-for-a-rake-task.md) +- [Specify How Random Array#sample Is](ruby/specify-how-random-array-sample-is.md) - [Split A Float Into Its Integer And Decimal](ruby/split-a-float-into-its-integer-and-decimal.md) - [Squeeze Out The Extra Space](ruby/squeeze-out-the-extra-space.md) - [String Interpolation With Instance Variables](ruby/string-interpolation-with-instance-variables.md) diff --git a/ruby/specify-how-random-array-sample-is.md b/ruby/specify-how-random-array-sample-is.md new file mode 100644 index 0000000..2c8a8f5 --- /dev/null +++ b/ruby/specify-how-random-array-sample-is.md @@ -0,0 +1,46 @@ +# Specify How Random Array#sample Is + +A typical use of the +[`sample`](https://ruby-doc.org/core-2.4.0/Array.html#method-i-sample) method +on [`Array`](https://ruby-doc.org/core-2.4.0/Array.html) will look something +like this: + +```ruby +> 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: + +```ruby +> chars.sample(6, random: Random) +=> ["F", "c", "g", "I", "w", "E"] +``` + +Or to get reproducible results, you can specify the `Random` seed: + +```ruby +> 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`](https://ruby-doc.org/stdlib-2.5.1/libdoc/securerandom/rdoc/SecureRandom.html). + +```ruby +> require 'securerandom' +=> true + +> chars.sample(6, random: SecureRandom) +=> ["3", "C", "o", "i", "K", "4"] +``` + +The +[`Array#shuffle`](https://ruby-doc.org/core-2.4.0/Array.html#method-i-shuffle) +method is another example of a method that can take a `random` option.