Skip to content
instance method

Array#sample

(?random: ::_Rand rng) -> Elem
(::int n, ?random: ::_Rand rng) -> ::Array[Elem]
sample(random: Random) → object
sample(count, random: Random) → new_ary

Returns random elements from self, as selected by the object given by the keyword argument random.

With no argument count given, returns one random element from self:

Example
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
a.sample # => 3
a.sample # => 8

Returns nil if self is empty:

Example
[].sample # => nil

With a non-negative numeric argument count given, returns a new array containing count random elements from self:

Example
a.sample(3) # => [8, 9, 2]
a.sample(6) # => [9, 6, 0, 3, 1, 4]

The order of the result array is unrelated to the order of self.

Returns a new empty array if self is empty:

Example
[].sample(4) # => []

May return duplicates in self:

Example
a = [1, 1, 1, 2, 2, 3]
a.sample(a.size) # => [1, 1, 3, 2, 1, 2]

Returns no more than a.size elements (because no new duplicates are introduced):

Example
a.sample(50) # => [6, 4, 1, 8, 5, 9, 0, 2, 3, 7]

The object given with the keyword argument random is used as the random number generator:

Example
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a.sample(random: Random.new(1))     # => 6
a.sample(4, random: Random.new(1))  # => [6, 10, 9, 2]

Related: see Methods for Fetching.

See also #rotate! #select #rotate #select! also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0