Things We Can Do with Arrays
Calculate with arrays.
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:
result = [:one, :two] + [:three, :four]puts result
Difference of arrays
We can subtract them from each other:
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:
puts ["Ruby", "Monstas"] * 3
Intersection of arrays
We can also find the intersection:
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:
puts("length is")puts [1, 2, 3].lengthputs("sort is")puts [3, 1, 2].sortputs("compact is")puts [1, nil, 2, 3, nil].compactputs("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]].transposeputs("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.