Method: Array#slice!
- Defined in:
- array.c
#slice!(index) ⇒ Object? #slice!(start, length) ⇒ nil #slice!(range) ⇒ nil
Removes and returns elements from self
.
With numeric argument index
given, removes and returns the element at offset index
:
a = ['a', 'b', 'c', 'd']
a.slice!(2) # => "c"
a # => ["a", "b", "d"]
a.slice!(2.1) # => "d"
a # => ["a", "b"]
If index
is negative, counts backwards from the end of self
:
a = ['a', 'b', 'c', 'd']
a.slice!(-2) # => "c"
a # => ["a", "b", "d"]
If index
is out of range, returns nil
.
With numeric arguments start
and length
given, removes length
elements from self
beginning at zero-based offset start
; returns the removed objects in a new array:
a = ['a', 'b', 'c', 'd']
a.slice!(1, 2) # => ["b", "c"]
a # => ["a", "d"]
a.slice!(0.1, 1.1) # => ["a"]
a # => ["d"]
If start
is negative, counts backwards from the end of self
:
a = ['a', 'b', 'c', 'd']
a.slice!(-2, 1) # => ["c"]
a # => ["a", "b", "d"]
If start
is out-of-range, returns nil
:
a = ['a', 'b', 'c', 'd']
a.slice!(5, 1) # => nil
a.slice!(-5, 1) # => nil
If start + length
exceeds the array size, removes and returns all elements from offset start
to the end:
a = ['a', 'b', 'c', 'd']
a.slice!(2, 50) # => ["c", "d"]
a # => ["a", "b"]
If start == a.size
and length
is non-negative, returns a new empty array.
If length
is negative, returns nil
.
With Range argument range
given, treats range.min
as start
(as above) and range.size
as length
(as above):
a = ['a', 'b', 'c', 'd']
a.slice!(1..2) # => ["b", "c"]
a # => ["a", "d"]
If range.start == a.size
, returns a new empty array:
a = ['a', 'b', 'c', 'd']
a.slice!(4..5) # => []
If range.start
is larger than the array size, returns nil
:
a = ['a', 'b', 'c', 'd']
a.slice!(5..6) # => nil
If range.start
is negative, calculates the start index by counting backwards from the end of self
:
a = ['a', 'b', 'c', 'd']
a.slice!(-2..2) # => ["c"]
If range.end
is negative, calculates the end index by counting backwards from the end of self
:
a = ['a', 'b', 'c', 'd']
a.slice!(0..-2) # => ["a", "b", "c"]
Related: see Methods for Deleting.
4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 |
# File 'array.c', line 4279
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));
}
|