Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
Array#repeated_combination
static VALUE
rb_ary_repeated_combination(VALUE ary, VALUE num)
{
rb_len_t n, i, len;
n = NUM2LEN(num); /* Combination size from argument */
RETURN_SIZED_ENUMERATOR(ary, 1, &num, rb_ary_repeated_combination_size); /* Return enumerator if no block */
len = RARRAY_LEN(ary);
if (n < 0) {
/* yield nothing */
}
else if (n == 0) {
rb_yield(rb_ary_new2(0));
}
else if (n == 1) {
for (i = 0; i < RARRAY_LEN(ary); i++) {
rb_yield(rb_ary_new3(1, RARRAY_AREF(ary, i)));
}
}
else if (len == 0) {
/* yield nothing */
}
else {
volatile VALUE t0;
rb_len_t *p = ALLOCV_N(rb_len_t, t0, n);
VALUE ary0 = ary_make_hidden_shared_copy(ary); /* private defensive copy of ary */
rcombinate0(len, n, p, n, ary0); /* compute and yield repeated combinations */
ALLOCV_END(t0);
RBASIC_SET_CLASS_RAW(ary0, rb_cArray);
}
return ary;
}
With a block given, calls the block with each repeated combination of length size of the elements of self; each combination is an array; returns self. The order of the combinations is indeterminate.
If a positive integer argument size is given, calls the block with each size-tuple repeated combination of the elements of self. The number of combinations is (size+1)(size+2)/2.
Examples:
-
sizeis 1:Examplec = [] [0, 1, 2].repeated_combination(1) {|combination| c.push(combination) } c # => [[0], [1], [2]]
-
sizeis 2:Examplec = [] [0, 1, 2].repeated_combination(2) {|combination| c.push(combination) } c # => [[0, 0], [0, 1], [0, 2], [1, 1], [1, 2], [2, 2]]
If size is zero, calls the block once with an empty array.
If size is negative, does not call the block:
[0, 1, 2].repeated_combination(-1) {|combination| fail 'Cannot happen' }
With no block given, returns a new Enumerator.
Related: see Methods for Combining.