Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Array#randomly_pick( n ) (See related posts)

Adds a handy function that lets you randomly pick n elements from an array.

class Array
  # If +number+ is greater than the size of the array, the method
  # will simply return the array itself sorted randomly
  def randomly_pick(number)
    sort_by{ rand }.slice(0...number)
  end
end

Comments on this post

levin posts on Feb 27, 2006 at 11:02
to randomize an Array, use:

sort_by { rand }
peter posts on Jun 02, 2006 at 13:39
Changed by admin.
inung posts on Feb 13, 2007 at 04:10
levin, cool... thx.

You need to create an account or log in to post comments to this site.


Click here to browse all 4858 code snippets

Related Posts