summaryrefslogtreecommitdiff
path: root/array.rb
diff options
context:
space:
mode:
authorNobuyoshi Nakada <nobu@ruby-lang.org>2020-01-26 18:34:18 +0900
committerNobuyoshi Nakada <nobu@ruby-lang.org>2020-01-26 19:45:58 +0900
commitd4e1d4e94e866d498ead1f370236df216917a6c7 (patch)
treea489f1382ade60a75ee704e063384eb8069ef012 /array.rb
parent29eb1b16028928139dcaa236beb6d351c85f434c (diff)
Moved Array#sample to rbinc
Diffstat (limited to 'array.rb')
-rwxr-xr-xarray.rb27
1 files changed, 27 insertions, 0 deletions
diff --git a/array.rb b/array.rb
index ed5779290f..25da88cde8 100755
--- a/array.rb
+++ b/array.rb
@@ -33,4 +33,31 @@ class Array
def shuffle(random: Random)
__builtin_rb_ary_shuffle(random);
end
+
+ # call-seq:
+ # ary.sample -> obj
+ # ary.sample(random: rng) -> obj
+ # ary.sample(n) -> new_ary
+ # ary.sample(n, random: rng) -> new_ary
+ #
+ # Choose a random element or +n+ random elements from the array.
+ #
+ # The elements are chosen by using random and unique indices into the array
+ # in order to ensure that an element doesn't repeat itself unless the array
+ # already contained duplicate elements.
+ #
+ # If the array is empty the first form returns +nil+ and the second form
+ # returns an empty array.
+ #
+ # a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
+ # a.sample #=> 7
+ # a.sample(4) #=> [6, 4, 2, 5]
+ #
+ # The optional +rng+ argument will be used as the random number generator.
+ #
+ # a.sample(random: Random.new(1)) #=> 6
+ # a.sample(4, random: Random.new(1)) #=> [6, 10, 9, 2]
+ def sample(n = (ary = false), random: Random)
+ __builtin_rb_ary_sample(random, n, ary)
+ end
end