Arrays
General Syntax:
If you want to save a range of numbers, or pack multiple values into one variable, then you use the data structure called an array. An array is a list of items between square brackets. Data inside an array does not have to be in any order, and arrays can hold any type of data, whether it be a string, an integer, booleans, objects, even additional arrays.
Array syntax looks like this:
Accessing Items in an Array:
You can access items inside an array like so: example_array[0]
. Arrays start counting at number 0. So the element in the first position is at index 0, then the seconds is at index 1, and the third is at index 2, etc.
Adding to An Array:
Adding to an array can be done in two ways: The first looks like this: example_array.push("string")
or example_array << "string"
.
Iterating over Arrays:
Iterating over arrays uses syntax that looks like this: example_array.each { |i| puts i }
Iterating over multi-dimensional arrays is a little bit different:
Last updated