Ruby Newbie homepage Ruby Newbie homepage

How to use

Quick guide

Official content
Calls the block, if given, with combinations of elements of self; returns self. The order of combinations is indeterminate.
When a block and an in-range positive Integer argument n (0 < n <= self.size) are given, calls the block with all n-tuple combinations of self.
Example:
a = [0, 1, 2]
a.combination(2) {|combination| p combination }
Output:
[0, 1]
[0, 2]
[1, 2]
Another example:
a = [0, 1, 2]
a.combination(3) {|combination| p combination }
Output:
[0, 1, 2]
When n is zero, calls the block once with a new empty Array:
a = [0, 1, 2]
a1 = a.combination(0) {|combination| p combination }
Output:
[]
When n is out of range (negative or larger than self.size), does not call the block:
a = [0, 1, 2]
a.combination(-1) {|combination| fail 'Cannot happen' }
a.combination(4) {|combination| fail 'Cannot happen' }
Returns a new Enumerator if no block given:
a = [0, 1, 2]
a.combination(2) # => #<Enumerator: [0, 1, 2]:combination(2)>
 
               static VALUE
rb_ary_combination(VALUE ary, VALUE num)
{
    long i, n, len;

    n = NUM2LONG(num);
    RETURN_SIZED_ENUMERATOR(ary, 1, &num, rb_ary_combination_size);
    len = RARRAY_LEN(ary);
    if (n < 0 || len < n) {
        /* 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 {
        VALUE ary0 = ary_make_shared_copy(ary); /* private defensive copy of ary */
        volatile VALUE t0;
        long *stack = ALLOCV_N(long, t0, n+1);

        RBASIC_CLEAR_CLASS(ary0);
        combinate0(len, n, stack, ary0);
        ALLOCV_END(t0);
        RBASIC_SET_CLASS_RAW(ary0, rb_cArray);
    }
    return ary;
}
            

Was this page useful?