method

zip

v2_4_6 - Show latest stable - Class: Array
zip(*args)
public

Converts any arguments to arrays, then merges elements of self with corresponding elements from each argument.

This generates a sequence of ary.size n-element arrays, where n is one more than the count of arguments.

If the size of any argument is less than the size of the initial array, nil values are supplied.

If a block is given, it is invoked for each output array, otherwise an array of arrays is returned.

a = [ 4, 5, 6 ]
b = [ 7, 8, 9 ]
[1, 2, 3].zip(a, b)   #=> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
[1, 2].zip(a, b)      #=> [[1, 4, 7], [2, 5, 8]]
a.zip([1, 2], [8])    #=> [[4, 1, 8], [5, 2, nil], [6, nil, nil]]

3Notes

Second example is correct

nachokb · Aug 6, 20092 thanks

@taryneast, the second example is correct. The receiver's #size limits the result's.

nachokb

question?

taryneast · May 7, 2009

Shouldn't the second example be:

[1,2].zip(a,b)         #=> [[1, 4, 7], [2, 5, 8], [nil,6,9]]

??? or am I missing something?

re: question?

hoff2 · Jan 22, 2014

Nope. Read it again:

This generates a sequence of self.size n-element arrays

If any of the arguments are longer than the receiver, the elements beyond the receiver's length are ignored