# Randomly select an element from an array

I have an array:

[1,2,3,4,5]

How do I randomly select an element from the array?

On Jun 22, 2006, at 21:46, David S. wrote:

I have an array:

[1,2,3,4,5]

How do I randomly select an element from the array?

irb(main):001:0> a = %w(foo bar baz)
=> [“foo”, “bar”, “baz”]
irb(main):002:0> a[rand(a.length)]
=> “bar”

– fxn

On Jun 22, 2006, at 2:46 PM, David S. wrote:

I have an array:

[1,2,3,4,5]

How do I randomly select an element from the array?

(the next is 2.)

class Array
def rand
self[Kernel.rand(size)]
end
end

[1,2,3,4,5].rand

jeremy

David S. wrote:

I have an array:

[1,2,3,4,5]

How do I randomly select an element from the array?

Array now has built-in random sorting so you could

[1,2,3,4,5].sort_by{rand}.last

2006/6/22, Chris H. [email protected]:

David S. wrote:

I have an array:

[1,2,3,4,5]

How do I randomly select an element from the array?

Array now has built-in random sorting so you could

[1,2,3,4,5].sort_by{rand}.last

While this certainly works it’s extremely inefficient.

robert

Robert K. schrieb:

[1,2,3,4,5].sort_by{rand}.last

While this certainly works it’s extremely inefficient.

robert

solution 1:

a = [1,2,3,4,5]
puts a[rand(a.size)]

solution 2:

class Array
def random_element
self[rand(self.size)]
end
end

puts [1,2,3,4,5].random_element

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.