How to Zip Arrays in Ruby: Syntax and Examples
In Ruby, you can zip arrays using the
zip method, which combines elements from multiple arrays into a single array of arrays. Each sub-array contains elements from the input arrays at the same index.Syntax
The zip method is called on one 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 position.
array1.zip(array2, array3, ...)- Returns an array of arrays combining elements by index.
ruby
array1.zip(array2)
Example
This example shows how to zip two arrays of equal length. The result is an array of pairs where each pair contains elements from both arrays at the same index.
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
A common mistake is expecting zip to fill missing values if arrays have different lengths. Ruby fills missing elements with nil. Also, zip does not modify the original arrays unless you use zip!.
ruby
a = [1, 2] b = ["x", "y", "z"] result = a.zip(b) puts result.inspect # Wrong: expecting no nils # Right: nil appears for missing elements # Also, zip does not change original arrays: a.zip(b) puts a.inspect
Output
[[1, "x"], [2, "y"], [nil, "z"]]
[1, 2]
Quick Reference
| Method | Description |
|---|---|
| zip(array2, ...) | Combines elements from arrays by index into sub-arrays |
| zip!(array2, ...) | Modifies the original array by zipping with others |
| zip with block | Processes zipped elements with a block instead of returning array |
Key Takeaways
Use
zip to combine arrays element-wise into an array of arrays.If arrays differ in length, missing elements become
nil in the result.zip returns a new array; use zip! to modify the original array.You can pass multiple arrays to
zip to combine more than two arrays.Using a block with
zip lets you process elements directly without creating a new array.