Robert Klemme schrieb: > 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 > > 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