DZone 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

Snippets has posted 5883 posts at DZone. View Full User Profile

Array#randomly_pick( N )

  • submit to reddit
        Adds a handy function that lets you randomly pick <i>n</i> 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)


Snippets Manager replied on Tue, 2007/02/13 - 4:07am

levin, cool... thx.

Snippets Manager replied on Mon, 2012/05/07 - 1:18pm

Changed by admin.

Snippets Manager replied on Mon, 2006/02/27 - 11:01am

to randomize an Array, use: sort_by { rand }