Skip to content
Browse files

Documentation for Array#sample

  • Loading branch information...
1 parent e7cc94a commit 0175c470c01c22db2f54c3912958bdb6c573d6cb @thiagopradi thiagopradi committed Jun 28, 2010
Showing with 7 additions and 0 deletions.
  1. +7 −0 activesupport/lib/active_support/core_ext/array/random_access.rb
View
7 activesupport/lib/active_support/core_ext/array/random_access.rb
@@ -1,5 +1,12 @@
class Array
# 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 <tt>nil</tt>. if +n+ is passed, returns <tt>[]</tt>.
+ #
+ # [1,2,3,4,5,6].sample # => 4
+ # [1,2,3,4,5,6].sample(3) # => [2, 4, 5]
+ # [].sample # => nil
+ # [].sample(3) # => []
def sample(n=nil)
return self[Kernel.rand(size)] if n.nil?
n = n.to_int

0 comments on commit 0175c47

Please sign in to comment.
Something went wrong with that request. Please try again.