问题描述
我想知道是否有这样做的更清洁的方式。基本上,我想从可变长度的数组选择一个随机元素。通常情况下,我会做这样的:
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)]
有什么是更可读/可简单更换第二行?或者是,最好的方式做到这一点。我想你可以做 myArray.shuffle.first
,但我只看到了 #shuffle
几分钟前的SO,我还没有实际使用它。
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.
推荐答案
只需使用的:
Just use Array#sample
:
[:foo, :bar].sample # => :foo, or :bar :-)
这是用Ruby 1.9.1+可用。为了还能够使用Ruby的早期版本使用它,你可以。
请注意在Ruby中1.8.7存在下,不幸的名称选
;它是在新版本改名所以你不应该使用的。
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.
这篇关于怎样随机从数组选?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!