Flowdock
method

sample

Importance_2
v3.2.13 - Show latest stable - 1 note - 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)  # => []
Show source
Register or log in to add new notes.
May 31, 2011 - (>= v3.0.0)
0 thanks

return random element

>> a = [1,2,3] >> a.sample 2

the same as

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