Here are a few things we can do with arrays.

Memorizing all of them is unnecessary; simply look things up in the documentation when needed. Prior experience with some of these is helpful, though.

We can use arithmetic operators on arrays to obtain other arrays.

Concatenation of arrays

We can concatenate the elements of two arrays:

Press + to interact
result = [:one, :two] + [:three, :four]
puts result

Difference of arrays

We can subtract them from each other:

Press + to interact
result = [1, 1, 2, 3, 4] - [1, 2]
puts result

Concatenating multiple copies of an array

We can multiply with a number for the following effect:

Press + to interact
puts ["Ruby", "Monstas"] * 3

Intersection of arrays

We can also find the intersection:

Press + to interact
puts ([1, 2, 3] & [2, 3, 4])

Other things to try out with arrays

We can also call various methods on the arrays.

Try out some of these below:

Press + to interact
puts("length is")
puts [1, 2, 3].length
puts("sort is")
puts [3, 1, 2].sort
puts("compact is")
puts [1, nil, 2, 3, nil].compact
puts("index is")
puts [4,9,20].index(9)
puts("rotate is")
puts [1, 2, 3, 4].rotate(2)
puts("transpose is")
puts [[1, 2, 3], [4, 5, 6], [7, 8, 9]].transpose
puts("join is")
puts ["We", "are", "one"].join(".")

In these examples, the method compact removes all nil values from the array on which it’s called. The transpose method works with a nested array and turns columns into rows and rows into columns. A very useful method is join.

It creates a string by combining all cell values (as strings), separated by the separator we specify.