method

sample

v3.2.8 - Show latest stable - Class: Array
sample(n=nil)
public

Backport of Array#sample based on Marc-Andre Lafortune’s github.com/marcandre/backports/ Returns a random element or n random elements from the array. If the array is empty and n is nil, returns nil. If n is passed and its value is less than 0, it raises an ArgumentError exception. If the value of n is equal or greater than 0 it returns [].

[1,2,3,4,5,6].sample     # => 4
[1,2,3,4,5,6].sample(3)  # => [2, 4, 5]
[1,2,3,4,5,6].sample(-3) # => ArgumentError: negative array size
           [].sample     # => nil
           [].sample(3)  # => []

1Note

return random element

korin · May 31, 2011
>> a = [1,2,3]
>> a.sample
2

the same as

>> a[rand(a.length - 1)]
1