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

push, pop, shift, unshift

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
🔒

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.