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.
Zip for combining arrays in 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.
names = ["Alice", "Bob", "Carol"] ages = [25, 30, 22] combined = names.zip(ages) # combined => [["Alice", 25], ["Bob", 30], ["Carol", 22]]
nil in the zipped result.letters = ["a", "b"] numbers = [1, 2, 3] zipped = letters.zip(numbers) # zipped => [["a", 1], ["b", 2], [nil, 3]]
nil.letters = ["a", "b", "c"] numbers = [1, 2] zipped = letters.zip(numbers) # zipped => [["a", 1], ["b", 2], ["c", nil]]
This program shows two arrays before and after using zip. It pairs each name with the matching age and prints them.
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
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.
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.