slice!(...)
public
Deletes the element(s) given by an index
(optionally with a length) or by a range.
Returns the deleted object, subarray, or nil if the index is out of range. Equivalent to:
def slice!(*args)
result = self[*args]
self[*args] = nil
result
end
a = [ "a", "b", "c" ]
a.slice!(1)
a
a.slice!(-1)
a
a.slice!(100)
a
Show source
/*
* call-seq:
* array.slice!(index) -> obj or nil
* array.slice!(start, length) -> sub_array or nil
* array.slice!(range) -> sub_array or nil
*
* Deletes the element(s) given by an index (optionally with a length)
* or by a range. Returns the deleted object, subarray, or
* <code>nil</code> if the index is out of range. Equivalent to:
*
* def slice!(*args)
* result = self[*args]
* self[*args] = nil
* result
* end
*
* a = [ "a", "b", "c" ]
* a.slice!(1)
* a
* a.slice!(-1)
* a
* a.slice!(100)
* a
*/
static VALUE
rb_ary_slice_bang(argc, argv, ary)
int argc;
VALUE *argv;
VALUE ary;
{
VALUE arg1, arg2;
long pos, len, orig_len;
rb_ary_modify_check(ary);
if (rb_scan_args(argc, argv, "11", &arg1, &arg2) == 2) {
pos = NUM2LONG(arg1);
len = NUM2LONG(arg2);
delete_pos_len:
if (len < 0) return Qnil;
orig_len = RARRAY_LEN(ary);
if (pos < 0) {
pos += orig_len;
if (pos < 0) return Qnil;
}
else if (orig_len < pos) return Qnil;
if (orig_len < pos + len) {
len = orig_len - pos;
}
if (len == 0) return rb_ary_new2(0);
arg2 = rb_ary_new4(len, RARRAY_PTR(ary)+pos);
RBASIC(arg2)->klass = rb_obj_class(ary);
rb_ary_splice(ary, pos, len, Qnil); /* Qundef in 1.9 */
return arg2;
}
if (!FIXNUM_P(arg1)) {
switch (rb_range_beg_len(arg1, &pos, &len, RARRAY_LEN(ary), 0)) {
case Qtrue:
/* valid range */
goto delete_pos_len;
case Qnil:
/* invalid range */
return Qnil;
default:
/* not a range */
break;
}
}
return rb_ary_delete_at(ary, NUM2LONG(arg1));
}