End of Life Ruby 3.0 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
array.c
View on GitHub ↗
VALUE
rb_ary_delete(VALUE ary, VALUE item)
{
VALUE v = item;
long i1, i2;
for (i1 = i2 = 0; i1 < RARRAY_LEN(ary); i1++) {
VALUE e = RARRAY_AREF(ary, i1);
if (rb_equal(e, item)) {
v = e;
continue;
}
if (i1 != i2) {
rb_ary_store(ary, i2, e);
}
i2++;
}
if (RARRAY_LEN(ary) == i2) {
if (rb_block_given_p()) {
return rb_yield(item);
}
return Qnil;
}
ary_resize_smaller(ary, i2);
ary_verify(ary);
return v;
}
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"