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?

···

--
Posted via http://www.ruby-forum.com/.

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 21:46, David Solis wrote:

I have an array:

[1,2,3,4,5]

How do I randomly select an element from the array?

You ask the entire ruby-talk mailing list: the answer is 4.
(the next is 2.)

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

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

jeremy

···

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

I have an array:

[1,2,3,4,5]

How do I randomly select an element from the array?

David Solis 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

···

--
Posted via http://www.ruby-forum.com/\.

While this certainly works it's extremely inefficient.

robert

···

2006/6/22, Chris Hulan <hulachr@hotmail.com>:

David Solis 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

--
Have a look: Robert K. | Flickr

Robert Klemme schrieb:

David Solis 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

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

···

2006/6/22, Chris Hulan <hulachr@hotmail.com>: