Skip to content
instance method

Array#zip

[U] (::_Each[U] arg) -> ::Array[[ Elem, U? ]]
(::_Each[untyped] arg, *::_Each[untyped] args) -> ::Array[::Array[untyped]]
[U] (::_Each[U] arg) { ([ Elem, U? ]) -> void } -> nil
(::_Each[untyped] arg, *::_Each[untyped] args) { (::Array[untyped]) -> void } -> nil
zip(*other_arrays) → new_array
zip(*other_arrays) {|sub_array| ... } → nil

With no block given, combines self with the collection of other_arrays; returns a new array of sub-arrays:

Example
[0, 1].zip(['zero', 'one'], [:zero, :one])
# => [[0, "zero", :zero], [1, "one", :one]]

Returned:

  • The outer array is of size self.size.

  • Each sub-array is of size other_arrays.size + 1.

  • The nth sub-array contains (in order):

    • The nth element of self.

    • The nth element of each of the other arrays, as available.

Example:

Example
a = [0, 1]
zipped = a.zip(['zero', 'one'], [:zero, :one])
# => [[0, "zero", :zero], [1, "one", :one]]
zipped.size       # => 2 # Same size as a.
zipped.first.size # => 3 # Size of other arrays plus 1.

When the other arrays are all the same size as self, the returned sub-arrays are a rearrangement containing exactly elements of all the arrays (including self), with no omissions or additions:

Example
a = [:a0, :a1, :a2, :a3]
b = [:b0, :b1, :b2, :b3]
c = [:c0, :c1, :c2, :c3]
d = a.zip(b, c)
pp d
# =>
[[:a0, :b0, :c0],
 [:a1, :b1, :c1],
 [:a2, :b2, :c2],
 [:a3, :b3, :c3]]

When one of the other arrays is smaller than self, pads the corresponding sub-array with nil elements:

Example
a = [:a0, :a1, :a2, :a3]
b = [:b0, :b1, :b2]
c = [:c0, :c1]
d = a.zip(b, c)
pp d
# =>
[[:a0, :b0, :c0],
 [:a1, :b1, :c1],
 [:a2, :b2, nil],
 [:a3, nil, nil]]

When one of the other arrays is larger than self, ignores its trailing elements:

Example
a = [:a0, :a1, :a2, :a3]
b = [:b0, :b1, :b2, :b3, :b4]
c = [:c0, :c1, :c2, :c3, :c4, :c5]
d = a.zip(b, c)
pp d
# =>
[[:a0, :b0, :c0],
 [:a1, :b1, :c1],
 [:a2, :b2, :c2],
 [:a3, :b3, :c3]]

With a block given, calls the block with each of the other arrays; returns nil:

Example
d = []
a = [:a0, :a1, :a2, :a3]
b = [:b0, :b1, :b2, :b3]
c = [:c0, :c1, :c2, :c3]
a.zip(b, c) {|sub_array| d.push(sub_array.reverse) } # => nil
pp d
# =>
[[:c0, :b0, :a0],
 [:c1, :b1, :a1],
 [:c2, :b2, :a2],
 [:c3, :b3, :a3]]

For an object in other_arrays that is not actually an array, forms the “other array” as object.to_ary, if defined, or as object.each.to_a otherwise.

Related: see Methods for Converting.

See also #values_at #unshift also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0