Arrays can hold multiple values. Variables can only hold one value.
Arrays can be used by enclosing multiple values in parentheses [], such as array name = ["value 1 "," value 2 "," value 3 "]
.
Each value is separated by a comma (,).
The method of preparing an array and storing the values has the following advantages.
--No need to define variables every time --The code is easier to read --The amount of code written is reduced
Not only can an array hold multiple values, but you can also assign those values to variables and output their contents.
(Example)
names = ["sawamura", "yamada", "tanaka"]
puts names
#=> sawamura
# yamada
# tanaka
As shown above, the values stored in the array are displayed in order.
The values stored in the array are numbered in order. This assigned number is called the ** index number **, and the value contained in the array is called the ** element **.
To retrieve a specific element, use the following syntax.
Array name [index number]
(Example)
names = ["sawamura", "yamada", "tanaka"]
puts names[0]
#=> sawamura
If you want to add an element to the array, you can add it with <<.
names = ["sawamura", "yamada", "tanaka"]
names << "sato"
puts names
#=> sawamura
# yamada
# tanaka
# sato
The push method, like the << method, adds a new element to the end of the array. The difference is that you can add only one element to the array with the << method, but you can add multiple elements at once with push.
(Example)
names = ["sawamura", "yamada", "tanaka"]
names.push("sato","wakabayashi")
puts names
#=> sawamura
# yamada
# tanaka
# sato
# wakabayashi
The shift method is a method that deletes the first element of the array.
(Example)
names = ["sawamura", "yamada", "tanaka"]
names.shift
puts names
#=> yamada
# tanaka
#index[0]confirm
#The index has also been updated
puts names[0]
#=> yamada
--Each array has an index that represents the element number --Use a form like names [0] to specify the index of the array and retrieve the element. --If you want to add an element to the array, use << to add it
Recommended Posts