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.
In this page:
Syntax
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
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
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
- Expecting
popandshiftto only read, when they remove and return the element and change the array. - Mixing up
shift(removes from the front) andpop(removes from the end). - Using
arr.push([7, 8])and expecting two new items, when it adds one nested array; useconcat.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: