如何從數組中隨機選擇? - 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章