Random subset of array
I often see use cases to randomly sample a subset from an array like this:
a = [3, 2, 6, 2, 6, 1] a.sample(rand(a.length + 1)) # => [2, 6, 6, 3]
I request extending
Array#sample to let it take an option (such as
:arbitrary) for doing that:
a.sample(:arbitrary) # => [2, 6, 6, 3]
or perhaps having an independent method (like
samples) to do it.
a.samples # => [2, 6, 6, 3]
Updated by trans (Thomas Sawyer) about 3 years ago
This definition of
#sample seems a bit limited. I know it aligns with the statical definition but it is very easy do another way:
shuffle.take(n). Also, the interface is a little odd because it can return an element or an Array. Maybe it would be better if it could return repeats.
[1,2,3,4].sample(10) => [1,2,4,3,3,4,2,1,2,3]
Then #sample could also take a block and return an enumerator when given no argument. To get one element it would be
But if backward compatibility needs to be preserved, then add this functionality by another name.
P.S. It would be weird but #sample could use negative numbers to allow repeating.