🎓 A1Learner
🔍
0 of 34 lessons completed

Ruby Arrays in Depth

Arrays can hold arrays inside them, and Ruby gives tools for cleaning and combining whole arrays at once. The beginner course covered building and reading arrays, and this lesson goes deeper.

Flattening a nested array

The rows array holds three smaller arrays. flatten joins them into one flat array.

rows = [[1, 2], [3, 4], [5]]
p rows.flatten

Flattening by levels

Plain flatten opens every level. flatten with 1 opens only the outer level.

deep = [1, [2, [3, [4]]]]
p deep.flatten
p deep.flatten(1)

Dropping nils and repeats

compact drops the nils from the list. uniq then drops the repeated numbers.

values = [3, nil, 1, nil, 3, 1]
p values.compact
p values.compact.uniq

Comparing two arrays

The & sign keeps the numbers that sit in both arrays. The - sign removes the numbers of the second array from the first.

a = [1, 2, 3, 4]
b = [3, 4, 5]
p a & b
p a - b

Pairing and rotating

zip pairs each name with the score at the same position. rotate moves the first day to the back, and rotate with 2 moves two days.

names = ["Ana", "Bo", "Cy"]
scores = [90, 85, 70]
p names.zip(scores)
days = ["Mon", "Tue", "Wed", "Thu"]
p days.rotate
p days.rotate(2)

Example

scores = [[80, nil, 90], [70, 80, nil]]
flat = scores.flatten.compact.uniq
p flat
p flat.rotate

Key points

  • flatten turns a nested array into one flat array.
  • flatten with a number flattens only that many levels.
  • compact drops every nil from an array.
  • uniq drops repeats and keeps the first copy of each item.
  • & keeps only the items that sit in both arrays.
  • - removes the items of the second array from the first.
  • zip pairs items from two arrays by position.
  • rotate moves the first items to the back.

In this example, the scores array holds two rows with nils and a repeated 80 inside them. flatten joins the rows, compact drops the nils, and uniq keeps one copy of each score. rotate then moves the first score to the back.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

The arrays are a = [1, 2, 3] and b = [2, 3, 4]. What does p a & b print?