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: code, howto, programming, ruby
1 Comment »
in ruby 1.9 you can also use the .sample method to do the same thing