An Array is essentially a list of numbered items.
The items are declared in a comma-separated list and enclosed in square brackets.
items = [“Apple”, “Orange”, “Banana”]
The code above declares an array named items containing three strings.
Each item has its own unique index with the first item at index zero.
To refer to an item, we need to refer to its index:
# outputs “Apple”
You can assign any array element a new value by using its index:
items = “Kiwi”
This will assign the element with index 1 the value “Kiwi”.
An array can contain different types of elements:
arr = [5, “Dave”, 15.88, false]
puts arr # 5
puts arr # “Dave”
puts arr[-1] # false
To add new elements to the array, you can use the << operator, which is typed as two less than signs:
arr << 8
This will add an element with the value 8 to the end of the array.
Alternatively, you can use the push and insert methods (we will learn more about methods in the coming module. For now, just remember that a method is code that performs an action).
This will add 8 to the end of the array.
The insert method allows you to insert the element at the desired position:
Similarly, there are pop and delete_at methods available to remove elements from the array.
The pop method removes the last element of the array.
arr = [1, 2, 3]
# [1, 2]
You can use the delete_at method to specify the index of the element to be removed:
arr = [2, 4, 6, 8]
# [2, 4, 8]
You can even access a range within the array using the range operators:
nums = [6, 3, 8, 7, 9]
# [3, 8, 7]
CLICK ON THE BUTTON BELOW TO GO TO THE RUBY MAIN COURSE PAGE.
© License: All Rights Reserved
CONTACT HOLLA TECH – LEARN SUPPORT