How do I pick randomly from an array?

2019-01-01 08:29发布

问题:

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:

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.

回答1:

Just use 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.



回答2:

myArray.sample(x) can also help you to get x random elements from the array.



回答3:

Random Number of Random Items from an Array

def random_items(array)
  array.sample(1 + rand(array.count))
end

Examples of possible results:

my_array = [\"one\", \"two\", \"three\"]
my_array.sample(1 + rand(my_array.count))

=> [\"two\", \"three\"]
=> [\"one\", \"three\", \"two\"]
=> [\"two\"]


回答4:

myArray.sample

will return 1 random value.

myArray.shuffle.first

will also return 1 random value.



回答5:

arr = [1,9,5,2,4,9,5,8,7,9,0,8,2,7,5,8,0,2,9]
arr[rand(arr.count)]

This will return a random element from array.

If You will use the line mentioned below

arr[1+rand(arr.count)]

then in some cases it will return 0 or nil value.

The line mentioned below

rand(number)

always return the value from 0 to number-1.

If we use

1+rand(number)

then it may return number and arr[number] contains no element.