AnyCompiler

Arrays

Arrays are written with square brackets, grow and shrink freely, and can be indexed from either end — arr[-1] is the last element, with no explicit arr.length - 1 arithmetic needed. push appends (as does the << operator, Ruby's idiomatic shovel), and pop removes and returns the last element.

arr = [1, 2, 3]
arr.push(4)
arr << 5
arr.pop
puts arr.inspect
puts arr[0]
puts arr[-1]
puts arr.length
Output
[1, 2, 3, 4]
1
4
4

Arrays include the Enumerable module (the same mixin mechanism covered in depth in lesson 16), which is where sort, max, sum, and dozens of other collection methods actually come from — they aren't special-cased into Array itself.

nums = [5, 3, 8, 1]
puts nums.sort.inspect
puts nums.max
puts nums.sum
Output
[1, 3, 5, 8]
8
17

Next: hashes — Ruby's key-value collection, almost always keyed with symbols rather than strings.

Practice exercise

Create nums = [1, 2, 3]. Push 4 and 5 onto it in one call, then print it joined by commas using .join(",").