Array Methods
Prerequisites: Arrays
Arrays come with a large set of methods. These cover most day-to-day work.
Example
nums = [5, 3, 8, 1, 3]
p nums.sort
p nums.sort.reverse
p nums.uniq
p nums.include?(8)
p nums.min
p nums.max
p nums.sum
p nums.count(3)
p nums.index(8)
p nums.first(2)
p nums.take(3)
p nums.join("-")
p nums.empty?
p [[1, 2], [3]].flatten
p [3, nil, 1, nil].compact
Expected output
[1, 3, 3, 5, 8]
[8, 5, 3, 3, 1]
[5, 3, 8, 1]
true
1
8
20
2
2
[5, 3]
[5, 3, 8]
"5-3-8-1-3"
false
[1, 2, 3]
[3, 1]
None of these change nums itself — each returns a new value. As with
strings, many have a ! version (sort!, uniq!, reverse!,
compact!) that changes the array in place.
Combining arrays
a = [1, 2, 3]
b = [3, 4]
p a + b
p a - b
p a & b
p a | b
[1, 2, 3, 3, 4]
[1, 2]
[3]
[1, 2, 3, 4]
& keeps elements in both arrays; | combines them without
duplicates.
The most powerful array methods — map, select, and reduce, which
take a block — get their own lesson after Blocks.
Common mistakes
- Calling
sort!inside a method on an array you were given, which unexpectedly changes the caller's data. Prefer the non-bang version unless changing it is the point.
Practice
Given scores = [72, 95, 88, 95, 60], print the highest score, the
average (as a float), and the unique scores in descending order.
Hint: the average is the sum divided by the count — make sure the division isn't integer division.
Show solution
scores = [72, 95, 88, 95, 60]
p scores.max
p scores.sum.fdiv(scores.length)
p scores.uniq.sort.reverse
95
82.0
[95, 88, 72, 60]