02-arrays.md 2.25 KB
Newer Older
1 2
# Array Variables

3 4 5 6 7
The **[]** syntax in Ion denotes that the contents within should be parsed as an
array expression. 
On using `let` keyword for array variables, all array arguments must be wrapped within the **[]** syntax. Otherwise it will be coerced into a space-separated string.
This design decision was made due to the possibility of an expanded array with one element 
being interpreted as a string.
8 9 10

Once created, you may call an array variable in the same manner as a string variable, but you
must use the **@** sigil instead of **$**. When expanded, arrays will be expanded into multiple
11 12 13
arguments. Hence it is possible to use arrays to set multiple arguments in commands. 

**NOTE** If an array is double quoted, it will be coerced into a string. This behavior is equivalent to invoking the `$join(array)` method.
14 15 16

**NOTE**: Brace expansions also create arrays.

Michael Aaron Murphy's avatar
Michael Aaron Murphy committed
17 18 19
## Create a new array
Arguments enclosed within brackets are treated as elements within an array.
```sh
20 21 22
{{#include ../../../tests/array_vars.ion:create_array}}
```
```txt
Michael Aaron Murphy's avatar
Michael Aaron Murphy committed
23 24 25 26
```

## Indexing into an array
Values can be fetched from an array via their position in the array as the index.
27
```sh
28 29 30 31
{{#include ../../../tests/array_vars.ion:index_array}}
```
```txt
{{#include ../../../tests/array_vars.out:index_array}}
Michael Aaron Murphy's avatar
Michael Aaron Murphy committed
32 33 34 35 36
```

## Copy array into a new array
Passing an array within brackets enables performing a deep copy of that array.
```sh
37 38 39 40
{{#include ../../../tests/array_vars.ion:array_copy}}
```
```txt
{{#include ../../../tests/array_vars.out:array_copy}}
Michael Aaron Murphy's avatar
Michael Aaron Murphy committed
41 42 43 44 45
```

## Array join
This will join each element of the array into a string, adding spaces between each element.
```sh
46
{{#include ../../../tests/array_vars.ion:array_join}}
47
```
48
```txt
49
{{#include ../../../tests/array_vars.out:array_join}}
Michael Aaron Murphy's avatar
Michael Aaron Murphy committed
50 51
```

52
## Array concatenation and variable stripping
53
The `++=` and `::=` operators can be used to efficiently concatenate an array in-place.
Michael Aaron Murphy's avatar
Michael Aaron Murphy committed
54
```sh
55
{{#include ../../../tests/array_vars.ion:array_concat_var_strip}}
56
```
57
```txt
58
{{#include ../../../tests/array_vars.out:array_concat_var_strip}}
Michael Aaron Murphy's avatar
Michael Aaron Murphy committed
59 60
```

61 62
## Practical array usage
Passing arrays as command arguments and capturing output of commands as arrays is useful.
63
```sh
64
{{#include ../../../tests/array_vars.ion:practical_array}}
65 66
```
```txt
67
{{#include ../../../tests/array_vars.out:practical_array}}
68
```