colors =["white", "black", "red", "green", "blue"]
There are 5 elements in an array called colors. Index numbers are assigned in order from the beginning, such as 0, 1, 2, 3 ...
When outputting
puts colors[2]
Then you can retrieve the third * red *.
animals = [["tuna", "octopus", "shark"], ["dog", "cat", "pig"], ["crow", "swan", "eagle"]]
It's like this. In the array called animals, there is an array containing 3 types of sea animals, 3 types of land animals, and 3 types of sky animals.
puts animals
↓
<Output result>
tuna
octopus
shark
dog
cat
pig
crow
swan
eagle
Sea animals are assigned an index number of 0.
puts animals[0]
↓
<Output result>
tuna
octopus
shark
Among the sea animals with index number 0 In addition, index number 1 is assigned.
puts animals[0][1]
↓
<Output result>
octopus
=> Represents what is output.
puts animals[0][0]
=> tuna
puts animals[0][1]
=> octopus
puts animals[0][2]
=> shark
puts animals[1][0]
=> dog
puts animals[1][1]
=> cat
puts animals[1][2]
=> pig
puts animals[2][0]
=> crow
puts animals[2][1]
=> swan
puts animals[2][2]
=> eagle
Even if the structure becomes complicated, it can be taken out in the same way.
countries = [["Japan", "America"], [["Brazil", "Russia"],["China", "India"]]]
There are two arrays in the array called countries Inside the second array is yet another array.
puts countries[0]
↓
<Output result>
Japan
America
puts countries[1]
↓
<Output result>
Brazil
Russia
China
India
puts countries[1][0]
↓
<Output result>
Brazil
Russia
puts countries[0][0]
=> Japan
puts countries[0][1]
=> America
puts countries[1][0][0]
=> Brazil
puts countries[1][0][1]
=> Russia
puts countries[1][1][0]
=> China
puts countries[1][1][1]
=> India
Even if it becomes more quadruple from here, the value can be retrieved with the same description.
Recommended Posts