shuffle!(*args)
public
Shuffles elements in self in place. If rng is given, it
will be used as the random number generator.
Show source
static VALUE
rb_ary_shuffle_bang(int argc, VALUE *argv, VALUE ary)
{
VALUE *ptr, opts, *snap_ptr, randgen = rb_cRandom;
long i, snap_len;
if (OPTHASH_GIVEN_P(opts)) {
randgen = rb_hash_lookup2(opts, sym_random, randgen);
}
if (argc > 0) {
rb_raise(rb_eArgError, "wrong number of arguments (%d for 0)", argc);
}
rb_ary_modify(ary);
i = RARRAY_LEN(ary);
ptr = RARRAY_PTR(ary);
snap_len = i;
snap_ptr = ptr;
while (i) {
long j = RAND_UPTO(i);
VALUE tmp;
if (snap_len != RARRAY_LEN(ary) || snap_ptr != RARRAY_PTR(ary)) {
rb_raise(rb_eRuntimeError, "modified during shuffle");
}
tmp = ptr[--i];
ptr[i] = ptr[j];
ptr[j] = tmp;
}
return ary;
}