问题:
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