Question
Given this Ruby array:
numbers = [0, 132, 432, 342, 234]
What is the simplest way to remove its first element (0)?
Short Answer
You will learn how to remove the first item from a Ruby array, when to use the mutating shift method, and how to create a new array without changing the original. You will also see related slicing techniques and common edge cases.
Concept
Ruby arrays are ordered collections: every value has a position, called an index. The first element has index 0.
To remove and return the first element from an array, use shift:
numbers = [0, 132, 432, 342, 234]
removed = numbers.shift
puts removed.inspect # 0
puts numbers.inspect # [132, 432, 342, 234]
shift changes the original array. This is called a mutating operation.
If you need the original array to remain unchanged, use drop(1) instead:
numbers = [0, 132, 432, 342, 234]
remaining = numbers.drop(1)
puts numbers.inspect # [0, 132, 432, 342, 234]
puts remaining.inspect # [132, 432, 342, 234]
Choosing whether to mutate an array matters in real programs. Other code may hold a reference to the same array and observe the change.
Mental Model
Think of an array as a queue of people waiting at a counter.
shiftserves the person at the front and removes them from the queue.drop(1)makes a new queue on paper that starts after the first person, while leaving the original queue untouched.
Use shift when the front item has truly been consumed. Use drop(1) when you only need a view or copy of what remains.
Syntax and Examples
Use shift to remove one item from the beginning of an array:
array.shift
It returns the removed value and changes array.
colors = ["red", "green", "blue"]
first_color = colors.shift
puts first_color # red
puts colors.inspect # ["green", "blue"]
You can remove multiple items by passing a count:
values = [10, 20, 30, 40]
first_two = values.shift(2)
puts first_two.inspect # [10, 20]
puts values.inspect # [30, 40]
For a non-mutating alternative, use drop:
values = [10, 20, 30, 40]
without_first = values.drop(1)
puts without_first.inspect # [20, 30, 40]
puts values.inspect # [10, 20, 30, 40]
Ruby also supports range slicing:
values = [10, 20, 30, 40]
without_first = values[1..]
puts without_first.inspect # [20, 30, 40]
Step by Step Execution
Consider this code:
numbers = [0, 132, 432, 342, 234]
first_number = numbers.shift
puts first_number
puts numbers.inspect
Execution trace:
numbersrefers to an array containing five values.numbers.shifttakes the value at index0, which is0.- That value is assigned to
first_number. - The original
numbersarray is changed. Its remaining values move forward. puts first_numberprints0.puts numbers.inspectprints[132, 432, 342, 234].
After shift, the new first element is 132, and it now has index 0.
Real World Use Cases
Removing the first array element is useful when items are processed in order:
- Job queues: take the next task waiting to be processed.
- Import scripts: read and remove a CSV header row before processing data rows.
- Command-line arguments: consume the next argument while parsing options.
- Simple game turns: remove the next player or card from the front of a list.
- Streaming batches: process the next item from a small in-memory work list.
Example: remove a header row from imported data.
rows = [
["name", "email"],
["Ava", "ava@example.com"],
["Noah", "noah@example.com"]
]
headers = rows.shift
puts headers.inspect # ["name", "email"]
puts rows.inspect # [["Ava", "ava@example.com"], ["Noah", "noah@example.com"]]
Real Codebase Usage
In application code, use shift when consuming the array is intentional and visible from the method's purpose.
def process_next_job!(jobs)
job = jobs.shift
return if job.nil?
perform(job)
end
The return if job.nil? guard clause safely handles an empty queue.
When a method should not alter data provided by its caller, prefer drop(1):
def data_rows(rows)
rows.drop(1)
end
A common parsing pattern is to duplicate before consuming when mutation is convenient but the caller's array must be preserved:
def parse_tokens(tokens)
remaining_tokens = tokens.dup
command = remaining_tokens.shift
[command, remaining_tokens]
end
For very large queues with frequent removals from the front, repeatedly calling shift may not be the best design. Consider a dedicated queue structure or maintain a read position, depending on the application.
Common Mistakes
A frequent mistake is expecting shift not to change the array.
numbers = [0, 132, 432]
result = numbers.shift
# numbers is now [132, 432], not [0, 132, 432]
Use drop(1) if the original values must stay intact.
Another mistake is using delete, which removes values by value rather than removing the first position:
numbers = [0, 132, 0, 432]
numbers.delete(0)
puts numbers.inspect # [132, 432]
delete(0) removes every 0. Use shift to remove only the first element.
Do not confuse pop and shift:
numbers = [0, 132, 432]
numbers.pop
puts numbers.inspect # [0, 132]
pop removes from the end, not the beginning.
Finally, shifting an empty array does not raise an error; it returns nil:
items = []
item = items.shift
puts item.nil? # true
Check for nil when an empty array is possible.
Comparisons
| Operation | Removes from original array? | Return value | Best use |
|---|---|---|---|
array.shift | Yes | First element, or nil if empty | Consume one item from the front |
array.shift(n) | Yes | Array of up to n first elements | Consume several front items |
array.drop(1) | No | New array without the first item | Keep the original unchanged |
array[1..] | No | New array from index 1 onward | Concise slicing syntax |
array.pop | Yes | Last element, or nil if empty | Consume one item from the end |
array.delete(value) | Yes | Removed value or values by matching value | Remove all occurrences of a value |
Use shift for positional removal at the front. Use delete only when the goal is to remove matching values throughout the array.
Cheat Sheet
# Remove and return the first element (mutates the array)
item = array.shift
# Remove and return the first n elements (mutates the array)
items = array.shift(n)
# Return a new array without the first element
rest = array.drop(1)
# Another non-mutating way to get everything after index 0
rest = array[1..]
# Read the first item without removing it
first = array.first
Rules to remember:
- Arrays start at index
0. shiftchanges the receiver array.shiftreturnsnilfor an empty array.shift(n)returns an array, even whennis1.drop(1)is safer when callers may still need the original array.popworks at the end of an array;shiftworks at the beginning.
FAQ
How do I remove the first element of an array in Ruby?
Call array.shift. It removes the first element, returns it, and changes the array.
Does Ruby shift modify the original array?
Yes. shift is a mutating method. Use array.drop(1) when you want a new array instead.
What does shift return on an empty Ruby array?
It returns nil.
How do I remove the first two elements in Ruby?
Use array.shift(2). It returns an array containing the removed items.
How do I get an array without its first item without mutating it?
Use array.drop(1) or array[1..].
Is delete(0) the same as removing the first element?
No. delete(0) removes all values equal to 0, wherever they occur. shift removes the element at the first position.
Should I use shift repeatedly for a large queue?
For small arrays, it is clear and practical. For heavy queue workloads, consider a queue-oriented design to avoid repeatedly removing from the front of a large array.
Mini Project
Description
Build a small support-ticket processor. Tickets are stored in arrival order, and the next ticket should be removed from the front when an agent starts working on it. This demonstrates using shift as a simple first-in, first-out queue.
Goal
Process the next support ticket safely and show the remaining tickets.
Requirements
Requirement 1
Keep learning
Related questions
Add a Default Value to an Existing Column in a Rails Migration
Learn how to add or change a default value on an existing database column using Rails Active Record migrations safely.
Calling a Class Method from an Instance in Ruby
Learn how to call a class method from an instance in Ruby using self.class, with examples, pitfalls, and practical usage patterns.
Calling an Overridden Monkey-Patched Method in Ruby
Learn how to call the original method when monkey patching in Ruby, including alias_method patterns, examples, pitfalls, and practical usage.