Skip to content
Justice Tech School

Ruby Arrays In Depth

Arrays grow automatically. Methods: push, pop, shift, unshift, insert, delete, include?, index, first, last, sort, reverse, uniq, compact, flatten and join. Negative indexes count from the end.

Example
a = [3, 1, 2]
a.push(4); a.unshift(0)
puts a.inspect, a[-1], a.first(2).inspect
puts a.sort.reverse.inspect
puts [1, [2, [3]], nil].flatten.compact.inspect
puts [1, 1, 2].uniq.inspect

Result

[0, 3, 1, 2, 4]
4
[0, 3]
[4, 3, 2, 1, 0]
[1, 2, 3]
[1, 2]

Exercise

Remove the last item.

a.

Quiz Test

What does a[-1] give?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.