juniorRuby

Explain how array modifiers like push, pop, shift, and unshift work.

Updated May 17, 2026

Short answer

push adds an element to the end; pop removes from the end. unshift adds an element to the beginning; shift removes from the beginning. All these modify the array in place.

Deep explanation

These methods allow Ruby arrays to act efficiently as stacks or queues. push (also written as <<) and pop operate on the tail end of the array, which is an O(1) amortized operation. unshift and shift insert and remove from the head (index 0) of the array, requiring an O(n) re-indexing of all subsequent elements in memory.

Real-world example

Implementing simple message queues or processing historical breadcrumbs where events are continuously appended and popped off as they are completed.

Common mistakes

  • Using `shift` or `unshift` inside loops on very large datasets without realizing it causes performance degradation due to element shifting in memory.

Follow-up questions

  • What does `push` return?
  • How can you append multiple elements at once using push?

More Ruby interview questions

View all →