Ruby example

How to remove an element from an array in Ruby

9 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Use delete: nums.delete(3) removes every element equal to 3 from nums and returns 3 (or nil if it wasn't there). To remove only the first one, use nums.delete_at(nums.index(3)); to get a new array and keep the original, write nums - [3]. For a condition, use reject { |n| … } (new array) or delete_if (in place), and compact removes nil.

Ruby has a method for every way of removing from an array, and the choice comes down to two questions: do you pick the element by value, by position or by a condition, and should the original array change or should you get a new one back? Python readers: there is no remove() that stops at the first match, and no del a[i]; JavaScript readers: no splice. The sections below cover removing by value with delete and -, by position (including all but the last element), by condition with reject and delete_if, dropping nil and blank values, and the bug you get when you delete inside each, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1Remove by value: delete, or - for a new arrayRecommended

array.delete(value) removes every element that is == to the value, changes the array in place, and returns the value (not the array). When nothing matches it returns nil, or the result of a block if you pass one. To remove only the first occurrence, find its position with index and remove that slot with delete_at. To leave the original alone, subtract a one-element array: array - [value] returns a new array without any copies of the value, and array - [a, b] removes several values at once.

delete_value.rb
nums = [3, 1, 3, 2, 3]

# delete removes every element equal to the value
p nums.delete(3)
p nums

# It returns nil when the value is not there
p nums.delete(9)
p nums.delete(9) { "not found" }

# Remove only the first occurrence: delete_at + index
letters = ["a", "b", "a", "c"]
i = letters.index("a")
letters.delete_at(i) if i
p letters

# - returns a new array and leaves the original alone
colors = ["red", "green", "red", "blue"]
p colors - ["red"]
p colors - ["red", "blue"]
p colors

# Careful: deleting nil returns nil either way
list = [1, nil, 2]
p list.delete(nil)
p list

Output

nums.delete(3) returns 3 and leaves [1, 2]: all three 3s are gone, which surprises Python readers used to list.remove. The if i guard matters because index returns nil for a missing value, and delete_at(nil) raises a TypeError. After both subtractions colors still prints all four colors. The last two lines show why the return value is a poor success test: deleting nil returns nil even though it did remove it. Compare the size before and after, or use include? first, when you need to know.

2Remove by position, or take all but the last

When you know where the element is, delete_at(i) removes it and returns it, slice!(start, length) removes a run of elements and returns them, pop removes from the end and shift from the front (both take a count). All of these change the array. To get a shorter copy instead, slice it: items[0...-1] or items[..-2] is every element but the last (the three-dot range excludes its end, and a beginless range like ..-2 needs Ruby 2.7 or later), first(n) and take(n) keep the first n, and drop(n) skips them.

by_position.rb
items = ["a", "b", "c", "d", "e"]

# All but the last element (new arrays)
p items[0...-1]
p items[..-2]
p items.first(items.size - 1)
p items.take(2)
p items.drop(1)
p ["only"][..-2]

# Remove by position (these change the array)
p items.delete_at(1)
p items
p items.delete_at(10)
p items.slice!(1, 2)
p items
p items.pop
p items.shift
p items

# pop and shift take a count
stack = [1, 2, 3, 4, 5]
p stack.pop(2)
p stack.shift(2)
p stack
p [].pop

Output

The three "all but the last" forms all print ["a", "b", "c", "d"], and a one-element array gives [] rather than an error. The slice forms are the safest on an empty array too: first(items.size - 1) becomes first(-1) there and raises ArgumentError: negative array size. delete_at returns the removed "b", and an index past the end gives nil instead of an error, as do pop and shift on an empty array. pop(2) returns the last two in their original order, [4, 5].

3Remove by condition: reject, delete_if and keep_if

reject returns a new array without the elements the block accepts, and select (also named filter) is its mirror image: it keeps them. Each has two in-place versions: reject! and delete_if, select! and keep_if. They differ only in the return value: the bang methods return nil when nothing was removed, while delete_if and keep_if always return the array. partition gives you the kept and the removed elements in one pass, and uniq removes duplicates in one line.

by_condition.rb
scores = [72, 45, 90, 38, 66]

# reject returns a new array without the matches
p scores.reject { |s| s < 50 }
p scores.select { |s| s >= 50 }
p scores

# reject! and delete_if change the array in place
p scores.reject! { |s| s < 50 }
p scores
p scores.reject! { |s| s < 50 }
p scores.delete_if { |s| s < 50 }

# keep_if / select! are the "keep these" forms
words = %w[apple kiwi banana fig]
words.keep_if { it.size > 3 }
p words
p words.select! { it.size > 3 }

# partition splits into kept and removed in one pass
passed, failed = [72, 45, 90, 38].partition { it >= 50 }
p passed, failed

# Duplicates: uniq keeps the first of each
p [1, 2, 2, 3, 1].uniq
p %w[Ann ann Bob].uniq(&:downcase)

Output

After reject and select, scores still holds all five numbers; after reject! it is [72, 90, 66]. The second reject! finds nothing to remove and returns nil, while delete_if returns the array, so never chain a call after a bang method (arr.reject! { … }.size crashes when nothing matched). The same holds for uniq! and compact!. it is the block's implicit parameter in Ruby 3.4 and later; on older versions write { |w| w.size > 3 }. uniq with a block compares the block's result, so "ann" counts as a copy of "Ann".

4Remove nil and blank values: compact and filter_map

compact returns a copy without the nil elements (and compact! does it in place); it keeps false, 0 and empty strings. The common case is mapping and then dropping the nils: filter_map (Ruby 2.7 and later) does both in one pass, keeping every truthy block result. Empty and whitespace-only strings need a condition: reject(&:empty?) for empty strings, and a block with strip to catch spaces and nil as well. Rails code writes reject(&:blank?) or compact_blank, but blank? comes from Rails' ActiveSupport and does not exist in plain Ruby.

compact_blank.rb
# compact drops nil (and only nil)
values = [1, nil, 2, nil, false, 0]
p values.compact
p values.compact!
p [1, 2].compact!

# map, then remove the nils: filter_map does both in one pass
users = [{ email: "[email protected]" }, { email: nil }, { email: "[email protected]" }]
p users.map { it[:email] }.compact
p users.filter_map { it[:email] }

# filter_map keeps every truthy block result
nums = [1, 2, 3, 4, 5, 6]
p nums.filter_map { it * 10 if it.even? }

# Blank strings: compact is not enough
lines = ["one", "", "two", nil, "   ", "three"]
p lines.compact
p lines.compact.reject(&:empty?)
p lines.reject { it.nil? || it.strip.empty? }

# The same without it, for Ruby before 3.4
p lines.reject { |s| s.to_s.strip.empty? }

Output

compact leaves [1, 2, false, 0]: false and 0 are values, not nil. compact! on an array with no nils returns nil, like reject!. Both email lines print ["[email protected]", "[email protected]"], but filter_map builds one array instead of two; it also drops false results, which is why the if without an else works as a filter. For strings, reject(&:empty?) still keeps " ", and only the strip versions remove it. s.to_s turns nil into "", so one test covers both.

5Removing while iterating: the skip bug

Deleting from an array inside its own each loop does not raise an error in Ruby. It silently skips elements: each walks by index, so when an element is removed the next one slides into the current slot and the loop moves past it. The fix is to let one method do the looping and the removing (delete_if, reject!), to loop over a copy made with dup, or to build a new array with reject and reassign it.

delete_while_iterating.rb
# The bug: deleting from the array you are looping over
nums = [2, 4, 6, 7]
nums.each do |n|
  puts "checking #{n}"
  nums.delete(n) if n.even?
end
p nums

# The fix: one method that loops and removes
nums = [2, 4, 6, 7]
nums.delete_if { |n| n.even? }
p nums

# Or loop over a copy and change the original
nums = [2, 4, 6, 7]
nums.dup.each { |n| nums.delete(n) if n.even? }
p nums

# Or build a new array and reassign
nums = [2, 4, 6, 7]
nums = nums.reject(&:even?)
p nums

Output

The loop prints only checking 2 and checking 6: removing 2 moved 4 into slot 0, which the loop had already visited, and removing 6 did the same to 7. The result, [4, 7], still holds an even number. All three fixes print [7]. The dup version calls delete, which scans the whole array each time, so on large arrays prefer delete_if or reject, which make a single pass.

6Which should you use?

MethodChanges the array?ReturnsBest for
arr.delete(x)Yesx, or nilEvery copy of a value, in place
arr - [x]NoNew arrayA copy without one or more values
arr.delete_at(arr.index(x))YesThe elementOnly the first copy (guard against nil)
delete_at / slice! / pop / shiftYesRemoved element(s)A known position, or either end
arr[..-2] / take / dropNoNew arrayAll but the last, or the first n
reject { … } / delete_if { … }reject: no; delete_if: yesArrayAny condition
compact / filter_mapNo (compact! does)New arrayDropping nil, or map and drop in one pass
each { arr.delete(…) }YesSkips elementsAvoid: use delete_if or reject

Frequently asked questions

How do I remove only the first occurrence of a value?

delete removes every copy, so find the position first: i = arr.index(x) and then arr.delete_at(i) if i. The guard matters because index returns nil for a missing value and delete_at(nil) raises a TypeError. Without changing the array, arr.dup.tap { |a| a.delete_at(a.index(x)) } gives a copy, as long as x is present.

Why does arr.delete(x).size give 8?

delete returns the removed value, not the array, so [1, 2, 3].delete(2).size calls Integer#size, which is the number of bytes in the machine representation of the number: 8. Call delete on its own line and use the array afterwards, or write (arr - [x]).size when you want a new array to chain on.

How do I remove an element at an index without changing the array?

delete_at changes the array, so build a copy: arr.reject.with_index { |_, i| i == 2 } or arr[0...2] + arr[3..]. For %w[a b c d] both give ["a", "b", "d"].

Is there blank? or compact_blank in Ruby?

Not in plain Ruby: blank?, present? and compact_blank come from Rails (ActiveSupport), and " ".blank? without Rails raises NoMethodError: undefined method 'blank?' for an instance of String. Use arr.reject { |s| s.to_s.strip.empty? } to drop nil, empty and whitespace-only strings.

How do I remove nil values from a hash?

Hash#compact works like the array version: { a: 1, b: nil, c: 3 }.compact returns {a: 1, c: 3}, and compact! changes the hash in place. For other conditions, reject { |k, v| … } and delete_if work on hashes too.

How do I remove all the values of another array?

Subtract it: arr - other removes every element that appears in other, all copies included. arr.difference(b, c) does the same for several arrays at once, so [1, 2, 3, 2].difference([2], [3]) is [1]. Both compare with eql? and hash, so 1 and 1.0 count as different values.

Run it yourself

Open any of these in the full Ruby editor to tweak, run and share.

Ruby playground