End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
Array#slice!
static VALUE
rb_ary_slice_bang(int argc, VALUE *argv, VALUE ary)
{
VALUE arg1;
long pos, len;
rb_ary_modify_check(ary);
rb_check_arity(argc, 1, 2);
arg1 = argv[0];
if (argc == 2) {
pos = NUM2LONG(argv[0]);
len = NUM2LONG(argv[1]);
return ary_slice_bang_by_rb_ary_splice(ary, pos, len);
}
if (!FIXNUM_P(arg1)) {
switch (rb_range_beg_len(arg1, &pos, &len, RARRAY_LEN(ary), 0)) {
case Qtrue:
/* valid range */
return ary_slice_bang_by_rb_ary_splice(ary, pos, len);
case Qnil:
/* invalid range */
return Qnil;
default:
/* not a range */
break;
}
}
return rb_ary_delete_at(ary, NUM2LONG(arg1));
}
Removes and returns elements from self.
When the only argument is an Integer n, removes and returns the nth element in self:
a = [:foo, 'bar', 2] a.slice!(1) # => "bar" a # => [:foo, 2]
If n is negative, counts backwards from the end of self:
a = [:foo, 'bar', 2] a.slice!(-1) # => 2 a # => [:foo, "bar"]
If n is out of range, returns nil.
When the only arguments are Integers start and length, removes length elements from self beginning at offset start; returns the deleted objects in a new Array:
a = [:foo, 'bar', 2] a.slice!(0, 2) # => [:foo, "bar"] a # => [2]
If start + length exceeds the array size, removes and returns all elements from offset start to the end:
a = [:foo, 'bar', 2] a.slice!(1, 50) # => ["bar", 2] a # => [:foo]
If start == a.size and length is non-negative, returns a new empty Array.
If length is negative, returns nil.
When the only argument is a Range object range, treats range.min as start above and range.size as length above:
a = [:foo, 'bar', 2] a.slice!(1..2) # => ["bar", 2] a # => [:foo]
If range.start == a.size, returns a new empty Array.
If range.start is larger than the array size, returns nil.
If range.end is negative, counts backwards from the end of the array:
a = [:foo, 'bar', 2] a.slice!(0..-2) # => [:foo, "bar"] a # => [2]
If range.start is negative, calculates the start index backwards from the end of the array:
a = [:foo, 'bar', 2] a.slice!(-2..2) # => ["bar", 2] a # => [:foo]