arr = [1, 2, 3] arr.push(4) arr.shift puts arr.inspect
The array starts as [1, 2, 3]. push(4) adds 4 at the end, making it [1, 2, 3, 4]. Then shift removes the first element (1), leaving [2, 3, 4].
arr = ['a', 'b', 'c'] arr.unshift('z') arr.pop puts arr.inspect
Starting with ['a', 'b', 'c'], unshift('z') adds 'z' at the front: ['z', 'a', 'b', 'c']. Then pop removes the last element 'c', resulting in ['z', 'a', 'b'].
arr = [10, 20, 30, 40] arr.pop arr.unshift(5) arr.push(50) arr.shift puts arr.inspect
Start: [10, 20, 30, 40]
pop removes 40 → [10, 20, 30]
unshift(5) adds 5 at front → [5, 10, 20, 30]
push(50) adds 50 at end → [5, 10, 20, 30, 50]
shift removes first element (5) → [10, 20, 30, 50]
arr = [1, 2, 3] arr.pop(-5) puts arr.inspect
The pop method can take an optional argument for number of elements to remove. However, if the argument is negative, Ruby raises an ArgumentError.
arr = [] arr.unshift(1) arr.push(2) arr.unshift(3) arr.pop arr.shift arr.push(4) arr.shift
Start: []
unshift(1) → [1]
push(2) → [1, 2]
unshift(3) → [3, 1, 2]
pop removes last (2) → [3, 1]
shift removes first (3) → [1]
push(4) → [1, 4]
shift removes first (1) → [4]
Final array has 1 element.