Skip to content

End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Array#sample

array.sample(random: Random) → object
array.sample(n, random: Random) → new_ary

Returns random elements from self.

When no arguments are given, returns a random element from self:

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

If self is empty, returns nil.

When argument n is given, returns a new Array containing n random elements from self:

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

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

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

But self may contain duplicates:

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

The argument n must be a non-negative numeric value. The order of the result array is unrelated to the order of self. Returns a new empty Array if self is empty.

The optional random argument will be 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]
See also #rotate! #select #rotate #select! also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0