A two-dimensional array is an array that has an array as an element.
#Example:
number_arrays = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
color_arrays = [["red", "yellow", "blue"], ["white", "black", "gray"]]
Two-dimensional (planar) data can be represented by using a two-dimensional array. Example: Expressing the state of squares (◯ or ✕) in a two-dimensional array
# ◯:1,✕: Set to 0
arrays = [
[1, 1, 0, 0],
[1, 1, 1, 1],
[0, 1, 1, 1],
[1, 1, 0, 1],
[1, 0, 1, 1]
]
A two-dimensional array can be created in the same way as a normal array.
#Directly define and create
arrays = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
#Define an empty array arrays and add an array in it to create
arrays = []
arrays << [1, 2, 3]
arrays << [4, 5, 6]
arrays << [7, 8, 9]
arrays #=> [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
To get an array in a two-dimensional array ** Variable name [index number of array to get] ** Describe as.
arrays = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
arrays[0] #=> [1, 2, 3]
arrays[1] #=> [4, 5, 6]
arrays[2] #=> [7, 8, 9]
Also, to get each element of an array in a two-dimensional array ** Variable name [Index number of array to be acquired] [Index number of element to be acquired] ** Describe as.
arrays = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
arrays[0][0] #=> 1
arrays[0][1] #=> 2
arrays[0][2] #=> 3
arrays[1][0] #=> 4
arrays[1][1] #=> 5
arrays[1][2] #=> 6
arrays[2][0] #=> 7
arrays[2][1] #=> 8
arrays[2][2] #=> 9
There are also methods for two-dimensional arrays. transpose You can use the transpose method to create a 2D array with the rows and columns of the 2D array swapped.
#Example:
arrays = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
#The array is represented by a plane as follows.
# arrays = [
# [1, 2, 3],
# [4, 5, 6],
# [7, 8, 9]
# ]
transposed_arrays = arrays.transpose
transposed_arrays #=> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
# transposed_The array is represented by a plane as follows.
# transposed_arrays = [
# [1, 4, 7],
# [2, 5, 8],
# [3, 6, 9]
# ]
flatten You can use the flatten method to create an array that flattens a two-dimensional array (separates the array inside).
#Example:
arrays = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened_arrays = arrays.flatten
flattened_arrays #=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
Recommended Posts