instance method
Array#rotate
(?::int count) -> ::Array[Elem]
rotate(count = 1) → new_array
array.c
View on GitHub ↗
static VALUE
rb_ary_rotate_m(int argc, VALUE *argv, VALUE ary)
{
VALUE rotated;
const VALUE *ptr;
long len;
long cnt = (rb_check_arity(argc, 0, 1) ? NUM2LONG(argv[0]) : 1);
len = RARRAY_LEN(ary);
rotated = rb_ary_new2(len);
if (len > 0) {
cnt = rotate_count(cnt, len);
ptr = RARRAY_CONST_PTR(ary);
len -= cnt;
ary_memcpy(rotated, 0, len, ptr + cnt);
ary_memcpy(rotated, len, cnt, ptr);
}
ARY_SET_LEN(rotated, RARRAY_LEN(ary));
return rotated;
}
Returns a new array formed from self with elements rotated from one end to the other.
With non-negative numeric count, rotates elements from the beginning to the end:
Example
[0, 1, 2, 3].rotate(2) # => [2, 3, 0, 1] [0, 1, 2, 3].rotate(2.1) # => [2, 3, 0, 1]
If count is large, uses count % array.size as the count:
Example
[0, 1, 2, 3].rotate(22) # => [2, 3, 0, 1]
With a count of zero, rotates no elements:
Example
[0, 1, 2, 3].rotate(0) # => [0, 1, 2, 3]
With negative numeric count, rotates in the opposite direction, from the end to the beginning:
Example
[0, 1, 2, 3].rotate(-1) # => [3, 0, 1, 2]
If count is small (far from zero), uses count % array.size as the count:
Example
[0, 1, 2, 3].rotate(-21) # => [3, 0, 1, 2]
Related: see Methods for Fetching.