Ruby's zip: A way to merge arrays

When you need to combine multiple arrays element by element in Ruby, the zip method is just what you need. It’s concise, expressive, and ideal for transforming structured data—especially when used with to_h or map.

What Is Array#zip?

The zip method combines two or more arrays by pairing their elements by index. It returns a new array of arrays, where each sub-array contains the elements from each original array at the same position.

Basic Syntax

1
array1.zip(array2, array3, ...)

Example:

1
2
3
4
5
a = [1, 2, 3]
b = ["a", "b", "c"]

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

Arrays of Different Lengths

When arrays are of different sizes, Ruby fills in the blanks with nil.

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

Real-World Use Cases

1. Labeling Time Components

Let’s say you have a string representing time and you want to label the components:

1
2
3
4
5
6
time_str = "09:00"
labels = ["hour", "minute"]
values = time_str.split(":", 2)

labeled_time = labels.zip(values).to_h
# => { "hour" => "09", "minute" => "00" }

Or in one elegant line:

1
2
["hour", "minute"].zip("09:00".split(":", 2)).to_h
# => { "hour" => "09", "minute" => "00" }

This is perfect for building JSON objects, logging, or parsing user input.

2. Creating Hashes from Keys and Values

1
2
3
4
5
keys = [:name, :age]
values = ["Alice", 30]

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

3. Performing Element-Wise Operations

You can use zip with map to perform operations across two arrays:

1
2
3
4
5
a = [1, 2, 3]
b = [4, 5, 6]

a.zip(b).map { |x, y| x + y }
# => [5, 7, 9]