I'm a Ruby beginner who's trying to add multiple categories to my hangman game.
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. *categories.sample.sample
(a splat) always retuns a string.
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
What you have should work, it's your categories
array that's not working. 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.
#sample returns one random element from you array
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.