← Back to Ruby Course | Chapter 4: Arrays | Lesson 2 of 7

push, pop, shift, unshift

push adds to the end of a list, pop removes from the end, shift removes from the front, and unshift adds to the front. It is like people joining or leaving both ends of a queue.
Syntax
ruby
array.push(value)      # or array << value
array.pop
array.shift
array.unshift(value)

push, pop, shift, unshift

push (or <<) adds an element to the end of an array, pop removes and returns the last element, shift removes and returns the first element, and unshift adds an element to the beginning.

These four methods let you use an array as a stack (push/pop) or a queue (push/shift). All of them mutate the array in place.

Note: << is a common shorthand for push, like arr << 5, and is very idiomatic in Ruby.

Example: push, pop, shift, unshift

markup
arr = [2, 3, 4]

arr.push(5)
arr << 6
arr.unshift(1)

puts arr.inspect

last = arr.pop
first = arr.shift

puts "Removed: #{first}, #{last}"
puts arr.inspect
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Expecting pop and shift to only read, when they remove and return the element and change the array.
  2. Mixing up shift (removes from the front) and pop (removes from the end).
  3. Using arr.push([7, 8]) and expecting two new items, when it adds one nested array; use concat.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.