How to quickly grab n random array elements

03 Jun 2013

I had an array filled with some hashes that contained product endorsement data. I then wanted to pull a couple of random endorsements out for display on a particular testimonials page.

I was ready to get down with some rand action, and then found out about Ruby’s sample method for arrays.

The following would return an array containing three randomly selected electronic music producers:

producers = ["Eric Prydz", "Maor Levi", "Wolfgang Gartner", "Daft Punk"]