Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

Array#shuffle

(?random: ::Array::_Rand) -> ::Array[Elem]
shuffle(random: Random) → new_array

Returns a new array containing all elements from self in a random order, as selected by the object given by the keyword argument random:

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

Duplicate elements are included:

Example
a =            [0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
a.shuffle # => [1, 0, 1, 1, 0, 0, 1, 0, 0, 1]
a.shuffle # => [1, 1, 0, 0, 0, 1, 1, 0, 0, 1]

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

Related: see Methods for Fetching.

See also #shuffle! #shift #shelljoin #size also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0