mirror of
https://github.com/jbranchaud/til
synced 2026-01-04 23:58:01 +00:00
Add Specify How Random Array Sample Is as a Ruby TIL
This commit is contained in:
@@ -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)
|
||||
|
||||
46
ruby/specify-how-random-array-sample-is.md
Normal file
46
ruby/specify-how-random-array-sample-is.md
Normal file
@@ -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.
|
||||
Reference in New Issue
Block a user