Modulor. Custom Software Solutions.
Facebook | Twitter | LinkedIn
Posted by: Serguei on January 14, 2011
Category: Ruby on Rails
Just found this Ruby Quicktip for getting a random element from an array. There are two ways you can do this.

Given an array @array

@array = [1,2,3,4,5]

You can obtain a random element from the array with the 'choice' method:

=> 3

You can also do it with the 'sample' method

=> 2

With the 'sample' method you can specify the number of random elements you want:


=> [4,1]

Happy coding.