Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
Array#sample
# File tmp/rubies/ruby-3.4.1/array.rb, line 95
def sample(n = (ary = false), random: Random)
if Primitive.mandatory_only?
# Primitive.cexpr! %{ rb_ary_sample(self, rb_cRandom, Qfalse, Qfalse) }
Primitive.ary_sample0
else
# Primitive.cexpr! %{ rb_ary_sample(self, random, n, ary) }
Primitive.ary_sample(random, n, ary)
end
end
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:
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] a.sample # => 3 a.sample # => 8
Returns nil if self is empty:
[].sample # => nil
With a non-negative numeric argument count given, returns a new array containing count random elements from self:
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:
[].sample(4) # => []
May return duplicates in self:
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):
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:
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.