Question

Remove the First Array Element in Ruby: shift, drop, and Slicing

rubyruby-on-rails

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.

  • shift serves 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.

Take Quiz

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:

  1. numbers refers to an array containing five values.
  2. numbers.shift takes the value at index 0, which is 0.
  3. That value is assigned to first_number.
  4. The original numbers array is changed. Its remaining values move forward.
  5. puts first_number prints 0.
  6. puts numbers.inspect prints [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"]]
Take Quiz

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

OperationRemoves from original array?Return valueBest use
array.shiftYesFirst element, or nil if emptyConsume one item from the front
array.shift(n)YesArray of up to n first elementsConsume several front items
array.drop(1)NoNew array without the first itemKeep the original unchanged
array[1..]NoNew array from index 1 onwardConcise slicing syntax
array.popYesLast element, or nil if emptyConsume one item from the end
array.delete(value)YesRemoved value or values by matching valueRemove 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.

Take Quiz

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.
  • shift changes the receiver array.
  • shift returns nil for an empty array.
  • shift(n) returns an array, even when n is 1.
  • drop(1) is safer when callers may still need the original array.
  • pop works at the end of an array; shift works 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.

Take Quiz

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

Take Quiz

Keep learning

Related questions

View more