How do I pick randomly from an array? How do I pick randomly from an array? ruby ruby

How do I pick randomly from an array?


Just use Array#sample:

[:foo, :bar].sample # => :foo, or :bar :-)

It is available in Ruby 1.9.1+. To be also able to use it with an earlier version of Ruby, you could require "backports/1.9.1/array/sample".

Note that in Ruby 1.8.7 it exists under the unfortunate name choice; it was renamed in later version so you shouldn't use that.

Although not useful in this case, sample accepts a number argument in case you want a number of distinct samples.


myArray.sample(x) can also help you to get x random elements from the array.


Random Number of Random Items from an Array

def random_items(array)  array.sample(1 + rand(array.count))end

Examples of possible results:

my_array = ["one", "two", "three"]my_array.sample(1 + rand(my_array.count))=> ["two", "three"]=> ["one", "three", "two"]=> ["two"]