0
0
RubyHow-ToBeginner · 3 min read

How to Use zip in Ruby: Simple Guide with Examples

In Ruby, zip combines elements from multiple arrays into a single array of arrays, pairing elements by their index. You call zip on one array and pass other arrays as arguments to merge them element-wise.
📐

Syntax

The zip method is called on an array and takes one or more arrays as arguments. It returns a new array where each element is an array containing elements from the original arrays at the same index.

  • array1.zip(array2, array3, ...)
  • Each inner array contains elements from each array at the same position.
  • If arrays have different lengths, missing values become nil.
ruby
array1.zip(array2, array3)
💻

Example

This example shows how to combine two arrays of names and ages using zip. It pairs each name with the corresponding age.

ruby
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
combined = names.zip(ages)
puts combined.inspect
Output
[["Alice", 25], ["Bob", 30], ["Charlie", 35]]
⚠️

Common Pitfalls

One common mistake is expecting zip to merge arrays like concatenation. Instead, it pairs elements by index. Also, if arrays have different lengths, shorter arrays fill missing spots with nil, which can cause unexpected nil values.

Another pitfall is modifying the original array unintentionally when using zip with a block, as it can change the receiver array.

ruby
a = [1, 2]
b = [3, 4, 5]
result = a.zip(b)
puts result.inspect

# Wrong: expecting concatenation
# puts (a + b).inspect

# Using zip with block does NOT modify receiver
arr = [1, 2, 3]
arr.zip([4, 5, 6]) { |x| x }
puts arr.inspect  # arr stays unchanged, zip with block returns nil
Output
[[1, 3], [2, 4], [nil, 5]] [1, 2, 3]
📊

Quick Reference

  • Purpose: Combine arrays element-wise.
  • Returns: New array of arrays.
  • Missing elements: Filled with nil.
  • With block: Yields each combined array, returns nil.

Key Takeaways

Use zip to pair elements from arrays by their index.
If arrays differ in length, missing elements become nil in the result.
Calling zip with a block yields each combined array but returns nil.
The original arrays are not changed by zip unless explicitly modified.
For concatenation, use + instead of zip.