[英]How do I choose a random element from a random array?
我是一個Ruby初學者,他試圖在我的劊子手游戲中添加多個類別。
我知道如何從數組中選擇一個隨機元素。 例如:
animals = ['dog', 'cat', 'mouse']
random = animals[rand(animals.length)]
puts random
但是,我想隨機選擇整個數組,然后從該隨機數組中選擇一個隨機元素。 例如:
animals = ['dog', 'cat', 'mouse']
planets = [['jupiter'], ['mars']]
fruits = [['apple'], ['orange'], ['mango']]
categories =[[animals], [planets], [fruits]]
#the code I tried was:
random_array = categories[rand(categories.length)]
random_element = random_array[rand(random_array.length)]
puts random_element
但這會產生一個完整的數組,而不是一個元素。 請幫忙! 謝謝
animals = ['dog', 'cat', 'mouse']
planets = [['jupiter'], ['mars']]
fruits = [['apple'], ['orange'], ['mango']]
categories = [animals, planets, fruits]
puts categories.sample.sample #=> jupiter
正如Sawa所說,這將返回一個字符串或一個子數組。 *categories.sample.sample
(一個splat)總是返回一個字符串。
你的代碼是正確的,但數組初始化不是。 這是你要做的:
animals = ['dog', 'cat', 'mouse']
planets = ['jupiter', 'mars']
fruits = ['apple', 'orange', 'mango']
categories = [animals, planets, fruits]
在你的代碼中, animals
是數組, planets
和fruits
是數組的數組,而categories
是三個數組的數組,每個數組中都有一個變量
你有什么應該工作,這是你的categories
數組不起作用。 它應該是:
categories =[animals, planets, fruits]
而不是數組中的數組混合。
為什么不把它們弄平或者是一種矯枉過正
a = (animals.flatten + fruits.flatten + planets.flatten)
r = a[rand(a.flatten.size)]
=> "dog"
您也可以使用更高效的<<
來連接數組。
使用Array#sample
方法 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.