method

sample

rails latest stable - Class: Array

Method deprecated or moved

This method is deprecated or moved on the latest stable version. The last existing version (v3.2.13) is shown here.

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