Flowdock
method

sample

Importance_2
v3.0.5 - Show latest stable - 1 note - Class: Array
sample(n=nil) public

Backport of Array#sample based on Marc-Andre Lafortune’s http://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, returns [].

  [1,2,3,4,5,6].sample    # => 4
  [1,2,3,4,5,6].sample(3) # => [2, 4, 5]
             [].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