Array#shift
Array#shift removes and returns the first element of an array. When called with a numeric argument n, it removes and returns the first n elements as a new array. All remaining elements shift down by one index position.
Basic Usage
fruits = ["apple", "banana", "cherry"]
first = fruits.shift
puts first # => "apple"
puts fruits # => ["banana", "cherry"]
Removing Multiple Elements
Pass an integer to remove and return multiple elements at once:
queue = [1, 2, 3, 4, 5]
batch = queue.shift(2)
puts batch # => [1, 2]
puts queue # => [3, 4, 5]
Behavior on Empty Arrays
Calling shift on an empty array returns nil. Calling shift(n) on an empty array returns an empty array [].
[].shift # => nil
[].shift(3) # => []
shift vs pop
shift removes from the beginning of the array (front of the queue). pop removes from the end (back of the queue).
colors = ["red", "green", "blue"]
colors.shift # => "red" — removes front
colors.pop # => "blue" — removes back
colors # => ["green"]
Practical Examples
Queue Simulation
shift is ideal for FIFO (first-in, first-out) queue processing:
task_queue = ["email", "report", "backup", "sync"]
while (task = task_queue.shift)
puts "Processing: #{task}"
end
# Processing: email
# Processing: report
# Processing: backup
# Processing: sync
puts task_queue.empty? # => true
Processing Records in Order
rows = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
{ id: 3, name: "Carol" }
]
# Process each row, leaving remaining rows for later
current = rows.shift
puts "Handling: #{current[:name]}" # => "Handling: Alice"
puts "Remaining: #{rows.size} rows" # => "Remaining: 2 rows"
Sliding Window
Extract consecutive chunks from a stream:
data = [10, 20, 30, 40, 50]
window = data.shift(3)
puts window # => [10, 20, 30]
# Continue processing with remaining data
batch = data.shift(2)
puts batch # => [40, 50]
Return Value
shiftreturns the removed element, ornilif the array is emptyshift(n)returns an array containing up tonremoved elements, or[]if empty
letters = ["a", "b", "c"]
one = letters.shift # => "a"
some = letters.shift(2) { |arr| arr.reverse } # => ["b", "c"] (block ignored)
puts letters # => []
Performance Note
shift is an O(n) operation because all elements after the removed one must be shifted down by one index. For large arrays with frequent removals from the front, consider require 'deque' for a true O(1) double-ended queue implementation, or use pop with the array reversed.
See Also
- /reference/array-methods/array-pop/ — remove and return the last element
- /reference/array-methods/array-push/ — append elements to the end
- /reference/enumerable/enumerable-take/ — take the first n elements without removing them