0
0
Rubyprogramming~5 mins

Zip for combining arrays in Ruby

Choose your learning style9 modes available
Introduction

Zip helps you join two or more lists side by side, pairing their items together. It makes it easy to work with related data from different lists.

You have two lists of names and ages and want to pair each name with the correct age.
You want to combine two lists of questions and answers to make a quiz.
You have separate lists of cities and their temperatures and want to see them together.
You want to loop through two lists at the same time to compare their items.
Syntax
Ruby
array1.zip(array2, array3, ...)

The method returns a new array where each element is an array of items from each input array at the same position.

If arrays have different lengths, missing values become nil in the zipped result.

Examples
Pairs each name with the corresponding age.
Ruby
names = ["Alice", "Bob", "Carol"]
ages = [25, 30, 22]
combined = names.zip(ages)
# combined => [["Alice", 25], ["Bob", 30], ["Carol", 22]]
When arrays have different lengths, missing values become nil in the zipped result.
Ruby
letters = ["a", "b"]
numbers = [1, 2, 3]
zipped = letters.zip(numbers)
# zipped => [["a", 1], ["b", 2], [nil, 3]]
When one array is shorter, missing values become nil.
Ruby
letters = ["a", "b", "c"]
numbers = [1, 2]
zipped = letters.zip(numbers)
# zipped => [["a", 1], ["b", 2], ["c", nil]]
Sample Program

This program shows two arrays before and after using zip. It pairs each name with the matching age and prints them.

Ruby
names = ["Anna", "Brian", "Cathy"]
ages = [28, 34, 22]

puts "Before zip:"
puts "Names: #{names}"
puts "Ages: #{ages}"

combined = names.zip(ages)

puts "\nAfter zip:"
combined.each do |name_age_pair|
  puts "Name: #{name_age_pair[0]}, Age: #{name_age_pair[1]}"
end
OutputSuccess
Important Notes

Time complexity is O(n), where n is the length of the longest array.

Space complexity is O(n) because it creates a new array with paired elements.

Common mistake: expecting zip to modify original arrays; it returns a new array instead.

Use zip when you want to combine arrays element-wise. Use other methods if you want to merge or concatenate arrays instead.

Summary

Zip pairs elements from multiple arrays by their positions.

It returns a new array of arrays, each containing one element from each input array.

Missing elements in shorter arrays become nil in the result.