Array#zip

Added in v3.0 · Updated March 13, 2026 · Array Methods
ruby array zip

The zip method combines elements from the caller with corresponding elements from one or more other arrays. It returns a new array of arrays, where each inner array contains one element from each array at the same index.

Basic Usage

numbers = [1, 2, 3]
letters = ['a', 'b', 'c']

numbers.zip(letters)
# => [[1, "a"], [2, "b"], [3, "c"]]

When the arrays have different lengths, zip stops at the shortest array:

short = [1, 2]
long = ['a', 'b', 'c', 'd']

short.zip(long)
# => [[1, "a"], [2, "b"]]

With Multiple Arrays

You can zip more than two arrays together:

a = [1, 2, 3]
b = ['a', 'b', 'c']
c = [:x, :y, :z]

a.zip(b, c)
# => [[1, "a", :x], [2, "b", :y], [3, "c", :z]]

Using with Blocks

Pass a block to iterate over the zipped results without creating an intermediate array:

[1, 2, 3].zip(['a', 'b', 'c']) do |num, letter|
  puts "\#{num} -> \#{letter}"
end

# Output:
# 1 -> a
# 2 -> b
# 3 -> c

Converting to Hashes

A common pattern is converting zipped arrays to hashes using to_h:

keys = [:name, :age, :city]
values = ['Alice', 30, 'Boston']

keys.zip(values).to_h
# => {:name => "Alice", :age => 30, :city => "Boston"}

This is equivalent to keys.zip(values) called with a block, or using Hash[]:

Hash[keys.zip(values)]
# => {:name => "Alice", :age => 30, :city => "Boston"}

With Unequal Lengths and Default Values

Since zip stops at the shortest array, you may need to pad shorter arrays:

a = [1, 2, 3, 4]
b = ['a', 'b']

# Pad b with nil
a.zip(b + [nil] * (a.length - b.length))
# => [[1, "a"], [2, "b"], [3, nil], [4, nil]]

Parameters

ParameterTypeDefaultDescription
*othersArrayOne or more arrays to zip with self

Return Value

Returns a new array of arrays. Each inner array contains elements at the same index from all arrays.

See Also