[英]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.