Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

Array#delete

(untyped object) -> Elem?
[S, T] (S object) { (S object) -> T } -> (Elem | T)
delete(object) → last_removed_object
delete(object) {|element| ... } → last_removed_object or block_return

Removes zero or more elements from self.

With no block given, removes from self each element ele such that ele == object; returns the last removed element:

Example
a = [0, 1, 2, 2.0]
a.delete(2) # => 2.0
a           # => [0, 1]

Returns nil if no elements removed:

Example
a.delete(2) # => nil

With a block given, removes from self each element ele such that ele == object.

If any such elements are found, ignores the block and returns the last removed element:

Example
a = [0, 1, 2, 2.0]
a.delete(2) {|element| fail 'Cannot happen' } # => 2.0
a                                             # => [0, 1]

If no such element is found, returns the block’s return value:

Example
a.delete(2) {|element| "Element #{element} not found." }
# => "Element 2 not found."

Related: see Methods for Deleting.

See also #cycle #delete_at #count #delete_if also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0