简体   繁体   English

如何从随机数组中选择随机元素?

[英]How do I choose a random element from a random array?

I'm a Ruby beginner who's trying to add multiple categories to my hangman game. 我是一个Ruby初学者,他试图在我的刽子手游戏中添加多个类别。

I know how to choose a random element from an array. 我知道如何从数组中选择一个随机元素。 For example: 例如:

animals = ['dog', 'cat', 'mouse']
random = animals[rand(animals.length)] 
puts random

However, I want to choose an entire array randomly, and then a single random element from that random array. 但是,我想随机选择整个数组,然后从该随机数组中选择一个随机元素。 For example: 例如:

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

But this puts an entire array, instead of one element. 但这会产生一个完整的数组,而不是一个元素。 Please help! 请帮忙! Thanks 谢谢

animals = ['dog', 'cat', 'mouse']
planets = [['jupiter'], ['mars']]
fruits = [['apple'], ['orange'], ['mango']]

categories = [animals, planets, fruits]
puts categories.sample.sample #=> jupiter

As Sawa remarks, this would return either a string or one of the sub-arrays. 正如Sawa所说,这将返回一个字符串或一个子数组。 *categories.sample.sample (a splat) always retuns a string. *categories.sample.sample (一个splat)总是返回一个字符串。

your code is correct, but array initialization is not. 你的代码是正确的,但数组初始化不是。 Here's what you have to do: 这是你要做的:

animals = ['dog', 'cat', 'mouse']
planets = ['jupiter', 'mars'] 
fruits = ['apple', 'orange', 'mango']

categories = [animals, planets, fruits]

In your code, animals is array, planets and fruits are arrays of arrays, and categories is array of three arrays, inside of each one is one of you variables 在你的代码中, animals是数组, planetsfruits是数组的数组,而categories是三个数组的数组,每个数组中都有一个变量

What you have should work, it's your categories array that's not working. 你有什么应该工作,这是你的categories数组不起作用。 It supposed to be: 它应该是:

categories =[animals, planets, fruits]

and not a mix of arrays within an array. 而不是数组中的数组混合。

Why not flatten them all or is that an overkill 为什么不把它们弄平或者是一种矫枉过正

a = (animals.flatten + fruits.flatten + planets.flatten)
r = a[rand(a.flatten.size)]
=> "dog"

You might also use the more efficient << to concatenate arrays. 您也可以使用更高效的<<来连接数组。

使用Array#sample方法

This should be the shortest and cleanest way to do it. 这应该是最短,最干净的方法。

animals = ['dog', 'cat', 'mouse']
planets = [['jupiter'], ['mars']]
fruits = [['apple'], ['orange'], ['mango']]

[animals, planets, fruits].flatten.sample

#flatten returns a new array with all elements but in just one dimension. #flatten返回一个包含所有元素但只有一个维度的新数组。

#sample returns one random element from you array #sample从您的数组中返回一个随机元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM