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

问题:

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. 我想你可以做myArray.shuffle.first ,但是几分钟前我只在#shuffle上看到#shuffle ,我还没有真正使用它。


解决方案:

参考一: https://en.stackoom.com/question/Ebrh
参考二: https://stackoom.com/question/Ebrh
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章