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 )

01.17.2006
| 19365 views |
  • 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)
  end
end
    

Comments

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

levin, cool... thx.

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

Changed by admin.

Snippets Manager replied on Mon, 2006/02/27 - 12:01pm

to randomize an Array, use: sort_by { rand }