如何从数组中随机选择? [英] How do I pick randomly from an array?

查看: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)]

是否有更易读/更简单的东西来替换第二行?或者这是最好的方法.我想你可以做 myArray.shuffle.first,但我几分钟前才在 SO 上看到 #shuffle,我还没有真正使用它.

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.

推荐答案

只需使用 Array#sample:

[:foo, :bar].sample # => :foo, or :bar :-)

它在 Ruby 1.9.1+ 中可用.为了也能够在早期版本的 Ruby 中使用它,您可以 require "backports/1.9.1/数组/样本".

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".

请注意,在 Ruby 1.8.7 中,它以不幸的名称 choice 存在;它在以后的版本中被重命名,所以你不应该使用它.

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.

尽管在这种情况下没有用,sample 接受一个数字参数,以防您需要多个不同的样本.

Although not useful in this case, sample accepts a number argument in case you want a number of distinct samples.

这篇关于如何从数组中随机选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆