Skip to content

Commit 7208fad

Browse files
committed
Add Specify How Random Array Sample Is as a Ruby TIL
1 parent 0b99434 commit 7208fad

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1396 TILs and counting..._
13+
_1397 TILs and counting..._
1414

1515
---
1616

@@ -1187,6 +1187,7 @@ _1396 TILs and counting..._
11871187
- [Single And Double Quoted String Notation](ruby/single-and-double-quoted-string-notation.md)
11881188
- [Skip Specific CVEs When Auditing Your Bundle](ruby/skip-specific-cves-when-auditing-your-bundle.md)
11891189
- [Specify Dependencies For A Rake Task](ruby/specify-dependencies-for-a-rake-task.md)
1190+
- [Specify How Random Array#sample Is](ruby/specify-how-random-array-sample-is.md)
11901191
- [Split A Float Into Its Integer And Decimal](ruby/split-a-float-into-its-integer-and-decimal.md)
11911192
- [Squeeze Out The Extra Space](ruby/squeeze-out-the-extra-space.md)
11921193
- [String Interpolation With Instance Variables](ruby/string-interpolation-with-instance-variables.md)
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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

Comments
 (0)