How to pick a random element from an Array

Here’s a nifty little patch to Ruby’s Array class to provide a method for picking an element at random:

class Array
  def random_pick
    self.sort_by { rand }.first
  end
end

So then you can do things like this:

def what_is_your_favorite_color?
  colors = [ 'red', 'blue', 'green', 'yellow', 'purple', 'pink', 'black' ]
  colors.random_pick
end

Please don’t ask my why I’m doing this. The answer has something to do with test data.


Posted: February 28th, 2011 by Neal Enssle
Tags: , , ,
1 Comment »

One Comment on “How to pick a random element from an Array”

  1. 1 geapi said at 12:19 pm on June 17th, 2011:

    in ruby 1.9 you can also use the .sample method to do the same thing


Leave a Reply

Viagra precio | Look for the most accurate heart rate monitor on beetsblu. | how to lose weight