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:
@array.choice
=> 3
You can also do it with the 'sample' method
@array.sample
=> 2
With the 'sample' method you can specify the number of random elements you want:
@array.sample(2)
=> [4,1]
Happy coding.
Given an array @array
@array = [1,2,3,4,5]
You can obtain a random element from the array with the 'choice' method:
@array.choice
=> 3
You can also do it with the 'sample' method
@array.sample
=> 2
With the 'sample' method you can specify the number of random elements you want:
@array.sample(2)
=> [4,1]
Happy coding.




