End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
Array#rotate
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_TRANSIENT(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.
When no argument given, returns a new Array that is like self, except that the first element has been rotated to the last position:
a = [:foo, 'bar', 2, 'bar'] a1 = a.rotate a1 # => ["bar", 2, "bar", :foo]
When given a non-negative Integer count, returns a new Array with count elements rotated from the beginning to the end:
a = [:foo, 'bar', 2] a1 = a.rotate(2) a1 # => [2, :foo, "bar"]
If count is large, uses count % array.size as the count:
a = [:foo, 'bar', 2] a1 = a.rotate(20) a1 # => [2, :foo, "bar"]
If count is zero, returns a copy of self, unmodified:
a = [:foo, 'bar', 2] a1 = a.rotate(0) a1 # => [:foo, "bar", 2]
When given a negative Integer count, rotates in the opposite direction, from end to beginning:
a = [:foo, 'bar', 2] a1 = a.rotate(-2) a1 # => ["bar", 2, :foo]
If count is small (far from zero), uses count % array.size as the count:
a = [:foo, 'bar', 2] a1 = a.rotate(-5) a1 # => ["bar", 2, :foo]