If you want to extract a subset of an array (i.e. numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
) you can easily do this with one of the following examples:
numbers[0..2]
will return [1, 2, 3]
numbers[3...-2]
will return [3, 4, 5, 6]
numbers[-2..]
will return [8, 9]
numbers[..]
will return [1, 2, 3, 4, 5, 6, 7, 8, 9]
With two dots (3..6), the range is inclusive [3, 4, 5, 6]
With three dots (3...6), the range excludes the end [3, 4, 5]
Adding a -
to the range will start the count at the end of the array
An omitted first index defaults to zero
An omitted second index defaults to the size of the array
The same syntax can be used with assignment to replace a segment of an array with new values
numbers[3..6] = [-3, -4, -5, -6]
The above row will replace the numbers array with the following : [1, 2, -3, -4, -5, -6, 7, 8, 9]