Quick Question: Random item from array

Well I think this is a quick question. I would like to select a random
item from an array. I’m thinking maybe I need to generate a random
number from 0 to array length. Actually I’m not exactly sure how to do
this since I can’t seem to find math.random/math.floor on ruby api?
Knowing ruby, there is probably a much easier way to do what I am trying
to do. Any ideas? Thanks.

On 6/17/06, Jordan I. [email protected] wrote:

Well I think this is a quick question. I would like to select a random
item from an array.

Kernel#rand is what you want (ri rand)

class Array
def random
at(rand(length))
end
end
=> nil

a = (0…10).to_a
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

(0…10).map { a.random }
=> [5, 7, 7, 7, 1, 4, 3, 5, 8, 7, 8]

(0…10).map { a.random }
=> [5, 1, 5, 2, 2, 6, 6, 8, 3, 9, 9]

(0…10).map { a.random }
=> [2, 10, 2, 5, 5, 0, 9, 5, 10, 4, 5]

martin