snippetrubyCritical
How do I pick randomly from an array?
Viewed 0 times
arrayrandomlyhowfrompick
Problem
I want to know if there is a much cleaner way of doing this. Basically, I want to pick a random element from an array of variable length. Normally, I would do it like this:
Is there something that is more readable / simpler to replace the second line? Or is that the best way to do it. I suppose you could do
myArray = ["stuff", "widget", "ruby", "goodies", "java", "emerald", "etc" ]
item = myArray[rand(myarray.length)]Is there something that is more readable / simpler to replace the second line? Or is that the best way to do it. I suppose you could do
myArray.shuffle.first, but I only saw #shuffle a few minutes ago on SO, I haven't actually used it yet.Solution
Just use
It is available in Ruby 1.9.1+. To be also able to use it with an earlier version of Ruby, you could
Note that in Ruby 1.8.7 it exists under the unfortunate name
Although not useful in this case,
Array#sample:[:foo, :bar].sample # => :foo, or :bar :-)It is available in Ruby 1.9.1+. To be also able to use it with an earlier version of Ruby, you could
require "backports/1.9.1/array/sample".Note that in Ruby 1.8.7 it exists under the unfortunate name
choice; it was renamed in later version so you shouldn't use that.Although not useful in this case,
sample accepts a number argument in case you want a number of distinct samples.Code Snippets
[:foo, :bar].sample # => :foo, or :bar :-)Context
Stack Overflow Q#3482149, score: 1289
Revisions (0)
No revisions yet.