Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Array#delete

array.delete(obj) → deleted_object
array.delete(obj) {|nosuch| ... } → deleted_object or block_return

Removes zero or more elements from self; returns self.

When no block is given, removes from self each element ele such that ele == obj; returns the last deleted element:

Example
s1 = 'bar'; s2 = 'bar'
a = [:foo, s1, 2, s2]
a.delete('bar') # => "bar"
a # => [:foo, 2]

Returns nil if no elements removed.

When a block is given, removes from self each element ele such that ele == obj.

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

Example
s1 = 'bar'; s2 = 'bar'
a = [:foo, s1, 2, s2]
deleted_obj = a.delete('bar') {|obj| fail 'Cannot happen' }
a # => [:foo, 2]

If no such elements are found, returns the block’s return value:

Example
a = [:foo, 'bar', 2]
a.delete(:nosuch) {|obj| "#{obj} not found" } # => "nosuch not found"
See also #deconstruct #delete_at #cycle #delete_if also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0