Random choice - eh, I mean sample - of an array’s elements

Sunday, January 16, 2011

Need a randomly chosen element from an array? There’s a method for that!
Array#choice
(Ruby 1.8.7) or
Array#sample
(Ruby > 1.8.7):

[1,2,3,4,5,6,7,8,9].choice
=> 5

[1,2,3,4,5,6,7,8,9].sample
=> 8
[1,2,3,4,5,6,7,8,9].sample(3)
=> [3,8,9]

Thanks to everyone who mentioned these methods
here
and
here.
via
http://rubyquicktips.tumblr.com/post/2702240316/random-choice-eh-i-mean-sample-of-an-arrays

This entry was tagged Ruby and tips

comments powered by Disqus

© 2009-2013 lxneng.com. All rights reserved. Powered by Pyramid

go to Top