push, pop, shift, unshift
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: