Flowdock
method

sample

Importance_2
Ruby on Rails latest stable (v4.0.2) - 1 note - 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)  # => []
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